【问题标题】:ViewData.Model in partial is null部分 ViewData.Model 为空
【发布时间】:2008-10-23 11:16:07
【问题描述】:

在我的主页(叫它index.aspx)我叫

<%Html.RenderPartial("_PowerSearch", ViewData.Model);%>

这里是viewdata.model != null 当我到达我的部分时:

<%=ViewData.Model%>

viewdata.model == null

什么给了?!

【问题讨论】:

    标签: c# asp.net-mvc model


    【解决方案1】:

    您是否尝试过只传入 ViewData 而不是 ViewData.Model?这是我在助手中使用的删减版(无耻地从 Storefront 系列中窃取):

        /// <summary>
        /// Renders a LoggingWeb user control.
        /// </summary>
        /// <param name="helper">Helper to extend.</param>
        /// <param name="control">Type of control.</param>
        /// <param name="data">ViewData to pass in.</param>
        public static void RenderLoggingControl(this System.Web.Mvc.HtmlHelper helper, LoggingControls control, object data)
        {
            string controlName = string.Format("{0}.ascx", control);
            string controlPath = string.Format("~/Controls/{0}", controlName);
            string absControlPath = VirtualPathUtility.ToAbsolute(controlPath);
            if (data == null)
            {
                helper.RenderPartial(absControlPath, helper.ViewContext.ViewData);
            }
            else
            {
                helper.RenderPartial(absControlPath, data, helper.ViewContext.ViewData);
            }
        }
    

    请注意,我传入的是当前 ViewData 而不是 Model。

    【讨论】:

    • 谢谢,成功了。我转换到 beta1 版本的另一个微妙举措。
    【解决方案2】:

    这是未经测试的:

    <%=Html.RenderPartial("_ColorList.ascx", new ViewDataDictionary(ViewData.Model.Colors));%>
    

    在这种情况下,您的控件视图需要特定于它的视图数据。如果您的控件想要一个名为 Colors 的模型上的属性,那么可能:

    <%=Html.RenderPartial("_ColorList.ascx", new ViewDataDictionary(new { Colors = ViewData.Model.Colors }));%>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-01-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-09
      相关资源
      最近更新 更多