【问题标题】:ASP.NET MVC - strongly typed view with partial views (view and partial views should also have access to some global data)ASP.NET MVC - 带有部分视图的强类型视图(视图和部分视图也应该可以访问一些全局数据)
【发布时间】:2009-04-10 02:35:15
【问题描述】:

考虑以下场景:

Action Edit() 被转发到 Edit.aspx 视图以呈现视图。

Edit.aspx 由 textbox1 和两个局部视图(又名视图用户控件)组成: part1.ascx(其中有 textbox2、textbox3) 和 part2.ascx(有 checkbox1 和 checkbox2)

您想为 Edit.aspx 提供一个强类型视图,例如,您使用 EditViewData 类。

您还需要 Edit.aspx、part1.ascx 和 part2.ascx 可以访问一些全局信息,例如 currentUserID、currentUserLanguage、currentUserTimezone。

问题:

  1. 如何构建 EditViewData 类?
  2. 如何将视图数据传递给视图和部分视图,以便在提交表单并返回到 Edit() http.post 操作时自动填充对象?
  3. 您将什么传递给 Edit() http.post 操作?

【问题讨论】:

    标签: asp.net-mvc


    【解决方案1】:

    您的视图数据应如下所示:

    public class EditViewData
    {
        public int currentUserID { get; set; }
        public string currentUserLanguage { get; set; }
        public string currentUserTimezone { get; set; }
        // ... other stuff
    }
    

    在你强输入你的 aspx 之后,你还需要强输入你的 ascxs。然后在你的 aspx 中,当你调用 RenderPartial 时,像往常一样调用:

    <% using (Html.BeginForm()) %>
    <% Html.RenderPartial("part1.ascx" ); %>
    <% Html.RenderPartial("part2.ascx" ); %>
    <%}%>
    

    它应该自动继承控件中的模型。请记住,您的 BeginForm 应该围绕您的两个控件 (ascxs)。

    【讨论】:

    • +1 - 一直以来,我一直在传递 this.Model 作为 partials 的 Model 参数。没想到它自动传下来了。不错。
    猜你喜欢
    • 2010-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-12
    • 2011-03-07
    • 1970-01-01
    相关资源
    最近更新 更多