In MVC do partial views inherit the models of their Parent views?

后端 未结 2 1378
长发绾君心
长发绾君心 2021-01-19 00:45

I\'m passing some data to a View from my controller, which I wish to display inside a partial view inside that View (don\'t ask, it\'s complicated). I know I probably should

相关标签:
2条回答
  • 2021-01-19 01:32

    You can pass the model into the partial view as a second parameter using the overload:

    @Html.Partial("viewname", Model)
    

    Nothing wrong with this approach IMO as its the whole point in strongly-typed views and the benefits they bring...

    0 讨论(0)
  • 2021-01-19 01:48

    Is this behaviour intended like that in WPF where child controls inherit the data context of their parent View?

    Yes.

    I see you are not currently passing any model to the Would it work to just inherit the layouts, and then not need to use the partial at all?

    If you want to keep using it like you are, maybe just be more explicit about it, and pass the current model to the partial.

    @Html.Partial("_IndexPartial", Model)
    

    If you look at the source for Html.Partial(view):

    public static MvcHtmlString Partial(this HtmlHelper htmlHelper, string partialViewName)
    {
        return Partial(htmlHelper, partialViewName, null /* model */, htmlHelper.ViewData);
    }
    

    It is passing the model via htmlHelper.ViewData, you can access the model in the same way in your view with @{ViewData.Model}, but this is NOT a good practice.

    0 讨论(0)
提交回复
热议问题