布局页面MVC中局部视图的控制器 [英] Controller for partial view in layout page MVC

查看:199
本文介绍了布局页面MVC中局部视图的控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要根据所选值在布局页面中动态设置横幅图像.我一直在研究,但似乎无法为布局页面使用控制器,因此我一直在使用局部视图,但显然缺少某些东西.我该怎么做?

I need to set a banner image in my layout page dynamically based on a selected value. I have been researching but it seems that i cannot have a controller for the layout page, so i have been looking at using a partial view but i am missing something apparently. How can i accomplish this?

布局页面

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title - My ASP.NET Application</title>
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")
</head>
<body>
    <div class="header">
        <div>
            @Html.Partial("_Header")
        </div>
    </div>
    <div class="container body-content">
        @RenderBody()
        <hr />
        <footer>
            <p>&copy; @DateTime.Now.Year - My ASP.NET Application</p>
        </footer>
    </div>

    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/bootstrap")
    @RenderSection("scripts", required: false)
</body>
</html>

局部视图

@model TicketPaymentsAzureMVC.Models.Client

<h1>Header</h1>
<img src="@Url.Content(Model.BannerUrl)" alt="Image" />

推荐答案

使用@Html.Partial()不会调用控制器方法,而只会呈现在局部代码中定义的html.默认情况下,它将模型从主视图传递到局部视图(除非您在第二个参数中指定),因此除非主视图中的模型为typeof TicketPaymentsAzureMVC.Models.Client,否则您的代码将引发异常.

Using @Html.Partial() does not call a controller method and just renders the html defined in the partial. By default it passes the model from the main view to the partial (unless you specify it in the 2nd parameter), so unless the model in the main view is typeof TicketPaymentsAzureMVC.Models.Client your code will throw an exception.

如果使用包含属性Client Client的视图模型(并在GET方法中填充该属性),则可以使用

If you use a view model that contains a property Client Client (and you populate that property in the GET method), then you could use

@Html.Partial("_Header", Model.Client)

Client的实例传递给局部对象.这意味着每个使用该布局的视图都需要该属性.

to pass an instance of Client to the partial. That would mean that every view using that layout would need that property.

更好的选择是使用@Html.Action()@{ Html.RenderAction(); }调用返回部分查询的服务器方法

A better option is to use @Html.Action() or @{ Html.RenderAction(); } to call a server method that returns the partial

[ChildActionOnly]
public ActionResult Header()
{
    Client model = ... // initialize your model and set the `BannerUrl` property
    return PartialView(_"Header", model);
}

并在布局中

@{ Html.RenderAction("Header", yourControllerName); }

这篇关于布局页面MVC中局部视图的控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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