开发者

ASP.Net MVC Displaying a session value in a master page

When I display a session value in a master page (<%: Session["companyname"].T开发者_如何学JAVAoString() %>) the following information is displayed on the page { CompanyName = TestCompany}. How do I get just the value?

Thanks for your help!


If you can show the code where the value is stored in the session, it's more likely that I could help. I would suggest, though, that you might want to reconsider using the value from the session directly in your view. It would be better, in my opinion, to have a base view model that all of your view models derive from that has the CompanyName property, and any other common properties required by your master page, on it. Your master page, then, could be strongly-typed to the base view model and you could use the values from the model. I've used this pattern with good success on a couple of projects. Couple it with a base controller where the common properties are populated for view results in OnActionExecuted(), it can be very effective in both reducing code duplication and the use of magic strings in your views.

Model:

public abstract class CommonViewModel
{
    public string CompanyName { get; set; }
    public string UserDisplayName { get; set; }
    ...
}

Controller:

public abstract class BaseController
{
    public override void OnActionExecuted( ActionExecutedContext filterContext )
    {
        if (filterContext.Result is ViewResult)
        {
            var model = filterContext.ViewData.Model as CommonViewModel;
            if (model != null)
            {
                 model.CompanyName = Session["CompanyName"] as string;
                 model.UserDisplayName = Session["UserDisplayName"] as string;
            }
        }
    }
}

Master Page:

<%@ Master Language="C#" Inherits="System.Web.Mvc.ViewMasterPage<Foo.CommonViewModel>" %>
<!-- ... -->
<div>
   <%: Model.CompanyName %>
</div>
<!-- ... -->
<div>
   <%: Model.UserDisplayName %>
</div>
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜