开发者

Why can't I share a variable between two content sections in an ASP.NET MVC View?

I have an ASP.NET MVC View with the typical TitleContent and MainContent, with a fairly complicated title that I want to calculate once and then share between these two content sections, like so:

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>
<%
  开发者_高级运维  var complicatedTitle = string.Format("{0} - {1}", Model.FirstThing, Model.SecondThing);
%>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    <%: complicatedTitle %>
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

    <h2><%: complicatedTitle %></h2>

</asp:Content>

This, however, doesn't work, as the resulting error message would say that only Content controls are allowed directly in a content page that contains Content controls.

The calculation definately belongs in the view. How do you solve this problem?


The reason the code cannot be outside a Content control is because it needs to be in a server-side section of some type for the server to be able to automatically render it.

I'd suggest that it would be more common for this title to be constructed in your Controller Action method and saved to ViewData.


Another way is by adding an HTML helper specifically to produce the well-formatted title.

public static string FormattedTitle(this HtmlHelper helper, string firstPart, string secondPart)
{
    return firstPart + secondPart;
}

and then invoke it with

<%: Html.FormattedTitle(firstPart, secondPart) %>


here's one way : [Edit: looks like this one results in a static field - so don't use this - sorry]

<Script runat="server" language="C#">
    string foo = "first thing " + " second thing";
</Script>

<asp:Content ContentPlaceHolderID="head" runat="server">
    <%= foo %>
</asp:Content>

<asp:Content ContentPlaceHolderID="body" runat="server">
    <%= foo %>
</asp:Content>

(note you can't use 'var' in Script)

and a second way :

  • Use code-behind to calculate the property with a ComplicatedTitle property that private to the view. You're still completely relying on the view to perform the logic, but taking it out of the HTML part of the view - after all your aspx and aspx.cs file end up becoming the same class in the end anyway!
  • Some people are freaked out by code in views, but I think it definitely has its place if you're cautious and sensible

and a third way :

i'm assuming you don't want to make a third property in your model but heres a quick and dirty way if it ever seems appropriate. at least your controller is not doing it, but this probably isn't the best way

public class MyModel {

   public string Prop1 {get;set;}
   public string Prop2 {get;set;}

   public string GetFormattedTitle() {
      return Prop1 + " - " + Prop2;
   }    
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜