ASP.NET MVC 2 中的部分视图问题

发布于 2024-08-30 01:09:23 字数 2695 浏览 5 评论 0原文

这是母版页:

<%@ Master Language="C#" Inherits="System.Web.Mvc.ViewMasterPage" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title><asp:ContentPlaceHolder ID="TitleContent" runat="server" /></title>
    <link href="../../Content/Site.css" rel="stylesheet" type="text/css" />

    <asp:ContentPlaceHolder ID="header1" runat="server" />
</head>

<body>
<div class="page">
    <div id="header">
        <div id="title">
            <h1>My MVC Application</h1>
        </div>

        <div id="logindisplay">
            <% Html.RenderPartial("LogOnUserControl"); %>
        </div> 

        <div id="menucontainer">

            <ul id="menu">              
                <li><%= Html.ActionLink("Home", "Index", "Home")%></li>
                <li><%= Html.ActionLink("About", "About", "Home")%></li>
                <li><%= Html.ActionLink("Imoveis", "Index", "Categoria")%></li>
                <li><%= Html.ActionLink("Admin", "Index", "Admin")%></li>
                <li><%= Html.ActionLink("User", "Index", "User")%></li>
            </ul>

        </div>
    </div>
    <div id="left">

     <% Html.RenderPartial("~/Views/Imovel/Pesquisa.ascx"); %>   

    </div>
    <div id="main">
        <asp:ContentPlaceHolder ID="MainContent" runat="server" />

        <div id="footer">
        </div>
    </div>
</div>
</body>
</html>

部分视图

  <%= Html.DropDownList("categoria_id", (SelectList)ViewData["Categoriass"], "--Selecciona um--")%>



            <div class="editor-label">
            <%= Html.LabelFor(model => model.categoria_id) %>
        </div>
        <div class="editor-field">
            <%= Html.DropDownListFor(model => model.categoria_id, (SelectList)ViewData["Categorias"], "--Selecciona um--")%>

            <%= Html.ValidationMessageFor(model => model.categoria_id) %>
        </div>

这就是问题:

    public ActionResult Index()
    {
        ViewData["Message"] = "Welcome to ASP.NET MVC!";

        **ViewData["Categoriass"] = new SelectList(catRepository.FindAllCategorias().AsEnumerable(), "id", "nome", 3);**



        return View();
    }

由于部分视图位于母版页中,我如何获取其模型?

this is the master page :

<%@ Master Language="C#" Inherits="System.Web.Mvc.ViewMasterPage" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title><asp:ContentPlaceHolder ID="TitleContent" runat="server" /></title>
    <link href="../../Content/Site.css" rel="stylesheet" type="text/css" />

    <asp:ContentPlaceHolder ID="header1" runat="server" />
</head>

<body>
<div class="page">
    <div id="header">
        <div id="title">
            <h1>My MVC Application</h1>
        </div>

        <div id="logindisplay">
            <% Html.RenderPartial("LogOnUserControl"); %>
        </div> 

        <div id="menucontainer">

            <ul id="menu">              
                <li><%= Html.ActionLink("Home", "Index", "Home")%></li>
                <li><%= Html.ActionLink("About", "About", "Home")%></li>
                <li><%= Html.ActionLink("Imoveis", "Index", "Categoria")%></li>
                <li><%= Html.ActionLink("Admin", "Index", "Admin")%></li>
                <li><%= Html.ActionLink("User", "Index", "User")%></li>
            </ul>

        </div>
    </div>
    <div id="left">

     <% Html.RenderPartial("~/Views/Imovel/Pesquisa.ascx"); %>   

    </div>
    <div id="main">
        <asp:ContentPlaceHolder ID="MainContent" runat="server" />

        <div id="footer">
        </div>
    </div>
</div>
</body>
</html>

Partial View

  <%= Html.DropDownList("categoria_id", (SelectList)ViewData["Categoriass"], "--Selecciona um--")%>



            <div class="editor-label">
            <%= Html.LabelFor(model => model.categoria_id) %>
        </div>
        <div class="editor-field">
            <%= Html.DropDownListFor(model => model.categoria_id, (SelectList)ViewData["Categorias"], "--Selecciona um--")%>

            <%= Html.ValidationMessageFor(model => model.categoria_id) %>
        </div>

This is the problem:

    public ActionResult Index()
    {
        ViewData["Message"] = "Welcome to ASP.NET MVC!";

        **ViewData["Categoriass"] = new SelectList(catRepository.FindAllCategorias().AsEnumerable(), "id", "nome", 3);**



        return View();
    }

Since the partial view is in the master page, how do I get its model?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

土豪我们做朋友吧 2024-09-06 01:09:23

我认为你应该创建一个 ActionFilter 并将其应用到你的控制器上。

创建一个像这样的动作过滤器

public class DataForMasterPageAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        //initiate your repository

           var catRepository = ...;

        //then create the viewdata like so

        filterContext.Controller.ViewData["Categorias"] = new SelectList(catRepository.FindAllCategorias().AsEnumerable(), "id", "nome", 3);
    }

}

然后将其应用到控制器上,它也将可用于所有动作。像这样;

[DataForMasterPage]
public class CategoriaController : Controller
{
      public ActionResult Index()
      {
            ViewData["Message"] = "Welcome to ASP.NET MVC!";
            return View();
      }
}

在部分视图上,您​​只需像往常一样调用 ViewData,无需更改任何内容

<div class="editor-label">
        <%= Html.LabelFor(model => model.categoria_id) %>
    </div>
    <div class="editor-field">
        <%= Html.DropDownListFor(model => model.categoria_id, (SelectList)ViewData["Categorias"], "--Selecciona um--")%>

        <%= Html.ValidationMessageFor(model => model.categoria_id) %>
    </div>

可能会出现性能问题,但这是避免在每个方法上设置 ViewData 的最简单方法之一。

I think you should create an ActionFilter and apply it on your controllers.

Create an action filter like this

public class DataForMasterPageAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        //initiate your repository

           var catRepository = ...;

        //then create the viewdata like so

        filterContext.Controller.ViewData["Categorias"] = new SelectList(catRepository.FindAllCategorias().AsEnumerable(), "id", "nome", 3);
    }

}

Then apply it on the controller and it will be available for all actions as well. Like so;

[DataForMasterPage]
public class CategoriaController : Controller
{
      public ActionResult Index()
      {
            ViewData["Message"] = "Welcome to ASP.NET MVC!";
            return View();
      }
}

On the partial view you just call the ViewData as usual, no need to change anything

<div class="editor-label">
        <%= Html.LabelFor(model => model.categoria_id) %>
    </div>
    <div class="editor-field">
        <%= Html.DropDownListFor(model => model.categoria_id, (SelectList)ViewData["Categorias"], "--Selecciona um--")%>

        <%= Html.ValidationMessageFor(model => model.categoria_id) %>
    </div>

Might have performance issues, but its one of the simplest ways to avoid setting the ViewData on every method.

情深已缘浅 2024-09-06 01:09:23

如果您需要在每个请求中查询它,您可以为控制器创建基类并在创建过程中设置它:

public class BaseController : Controller
{
    public BaseController()
    {
        var catRepository = ...;
        ViewData["Categoriass"] = new SelectList(catRepository.FindAllCategorias().AsEnumerable(), "id", "nome", 3);
    }
}

这并不是真正有效,因为它将与每个控制器一起执行。您还可以创建设置 ViewData 的操作过滤器并在需要时应用它。

You can create base class for your controllers and set it during creation if you need to query for it with every request:

public class BaseController : Controller
{
    public BaseController()
    {
        var catRepository = ...;
        ViewData["Categoriass"] = new SelectList(catRepository.FindAllCategorias().AsEnumerable(), "id", "nome", 3);
    }
}

That is not really efficient,because it will be executed with every controller. You can also create action filter which sets ViewData and apply it where needed.

镜花水月 2024-09-06 01:09:23

我尝试过 Nick Masao & LukLed 解决方案,两者都有效。

但是,视图数据是为母版页设置的,在我的例子中,我假设母版页将呈现每个页面。

我必须
应用 [DataForMasterPage] 属性(Nick Masao 的解决方案)或
或者
继承BaseController(LukLed的解决方案)
在每个视图的控制器上。

那么,是否可以创建一个类并调用 Global.asax Application_Start 事件以使其每次都设置 viewdata ?

I have try Nick Masao & LukLed solutions, both of them are works.

However, the viewdata is set for masterpage, in my case, i assume masterpage will render every page.

I have to
apply the [DataForMasterPage] attribute (Nick Masao's solutions) or
or
inherits the BaseController (LukLed's solutions)
on every View's Controller.

So, is it possible create a Class and invoke on Global.asax Application_Start event to make it Set viewdata everytimes?

秉烛思 2024-09-06 01:09:23

您还可以创建一个 ContentPlaceHolder,在其中渲染部分视图并从底层页面调用 RenderPartial()。这样您就可以像往常一样传递模型。

You could also create a ContentPlaceHolder where you want the partial view to render and call the RenderPartial() from the underlying pages. That way you can pass the model as usual.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文