我怎么能写动态数据的页面布局在MVC 3剃须刀? [英] How can I write dynamic data to page layout in MVC 3 Razor?

查看:172
本文介绍了我怎么能写动态数据的页面布局在MVC 3剃须刀?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有MVC 3 C#项目剃刀引擎。哪些途径和,我想,最好的做法来编写动态数据到_Layout.cshtml?

I have MVC 3 C# project with Razor engine. What are the ways and, I guess, the best practices to write dynamic data to the _Layout.cshtml?

例如,也许我想在我的网站的右上角显示用户的名字,这个名字是从会话,数据库,或任何未来基于什么用户登录。

For example, maybe I'd like to display user's name in the upper right corner of my website, and that name is coming from Session, DB, or whatever based on what user is logged in.

感谢你。

更新:我也找上呈现一定的数据到布局的元素一个很好的做法。例如,如果我需要渲染一个特定的CSS文件根据登录用户的凭据。

UPDATE: I'm also looking for a good practice on rendering certain data into the element of the Layout. For example, if I need to render a specific CSS file depending on the logged-in user's credentials.

(对于上面的例子,我想使用URL佣工。)

(For the example above, I thought of using Url Helpers.)

推荐答案

Visual Studio创建默认的Internet应用程序中使用_LogOnPartial.cshtml做正是这一点。

The default internet application created by visual studio use _LogOnPartial.cshtml to do exactly this.

用户名值在HomeController中的登录操作设置

The user Name value is set in the LogOn action of the HomeController

$ C $下_LogOnPartial.cshtml

Code for _LogOnPartial.cshtml

@if(Request.IsAuthenticated) {
    <text>Welcome <strong>@User.Identity.Name</strong>!
    [ @Html.ActionLink("Log Off", "LogOff", "Account") ]</text>
}
else {
    @:[ @Html.ActionLink("Log On", "LogOn", "Account") ]
}

User.Identity是ASPNET成员提供的一部分。

User.Identity is part of the aspnet Membership provider.

code为_Layout.cshtml

Code for the _Layout.cshtml

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>@ViewBag.Title</title>
    <link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
    <script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/modernizr-1.7.min.js")" type="text/javascript"></script>
</head>
<body>
    <div class="page">
        <header>
            <div id="title">
                <h1>Test</h1>
            </div>
            <div id="logindisplay">
                @Html.Partial("_LogOnPartial")
            </div>
            <nav>
                <ul id="menu">
                </ul>
            </nav>
        </header>
        <section id="main">
            @RenderBody()
        </section>
        <footer>
        </footer>
    </div>
</body>
</html>

code代表的AccountController登录行动

Code for the AccountController Logon Action

[HttpPost]
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                if (Membership.ValidateUser(model.UserName, model.Password))
                {
                    FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
                    if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                        && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        return RedirectToAction("Index", "Home");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "The user name or password provided is incorrect.");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

$ C $下ApplicationViewPage类

Code for ApplicationViewPage class

public abstract class ApplicationViewPage<T> : WebViewPage<T>
    {
        protected override void InitializePage()
        {
            SetViewBagDefaultProperties();
            base.InitializePage();
        }

        private void SetViewBagDefaultProperties()
        {
            ViewBag.LayoutModel = new LayoutModel(Request.ServerVariables["SERVER_NAME"]);
        }

    }

以上code让我有持有我LayoutModel类的一个实例,在每一个页面一个ViewBag.LayoutModel。

The above code allow me to have a ViewBag.LayoutModel that hold an instance of my LayoutModel class in every page.

下面是一个code我LayoutModel类

Here is a code for my LayoutModel class

public class LayoutModel
    {
        public string LayoutFile { get; set; }
        public string IpsTop { get; set; }
        public string IpsBottom { get; set; }
        public string ProfileTop { get; set; }
        public string ProfileBottom { get; set; }

        public LayoutModel(string hostname)
        {
            switch (hostname.ToLower())
            {
                default:

                    LayoutFile = "~/Views/Shared/_BnlLayout.cshtml";
                    IpsBottom = "~/Template/_BnlIpsBottom.cshtml";
                    IpsTop = "~/Template/_BnlTop.cshtml";
                    ProfileTop = "~/Template/_BnlProfileTop.cshtml";
                    break;

                case "something.com":
                    LayoutFile = "~/Views/Shared/_Layout.cshtml";
                    IpsBottom = "~/Template/_somethingBottom.cshtml";
                    IpsTop = "~/Template/_somethingTop.cshtml";
                    ProfileTop = "~/Template/_somethingProfileTop.cshtml";
                    break;
            }
        }
    }

下面是code到视图

@{
    ViewBag.Title = "PageTitle";
    Layout = @ViewBag.LayoutModel.LayoutFile; 
}
@using (Html.BeginForm())
{
    <span class="error">@ViewBag.ErrorMessage</span>
    <input type="hidden" name="Referrer" id="Referrer" value="@ViewBag.Referrer" />
    html stuff here       
}

请参考以下问题的更多细节。请确保您修改你的web.config描述有:<一href="http://stackoverflow.com/questions/5453327/how-to-set-viewbag-properties-for-all-views-without-using-a-base-class-for-contro">How不使用一个基类控制器设置ViewBag属性所有意见?

这篇关于我怎么能写动态数据的页面布局在MVC 3剃须刀?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆