简体   繁体   中英

ViewData.Model in partial is null

In my main page (call it index.aspx ) I call

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

Here the viewdata.model != null When I arrive at my partial:

<%=ViewData.Model%>

Says viewdata.model == null

What gives?!

Have you tried just passing in ViewData instead of ViewData.Model? This is an abridged version what I use in my helpers (shamelessly stolen from the Storefront series):

    /// <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);
        }
    }

Note that I pass in the current ViewData and not the Model.

This is untested:

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

Your control view is expecting view data specific to it in this case. If your control wants a property on the model called Colors then perhaps:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM