In MVC, partial views inherit models from their parent views?

I am passing some data to a view from my controller, which I want to display inside a partial view inside this view (don't ask, it's complex). I know that I probably shouldn't even pass the model to a view that would seem for another view, but I noticed that the partial view actually inherits the model from the parenmt View parameter:

public ActionResult Index(){ Person p = new Person { FName = "Mo", LName = "Sep" }; return View(p); 

}

Then inside my Index View I have:

 <h2>Index</h2> @Html.Partial("_IndexPartial") 

and Inside _IndexPartial I have:

 @Model.FName 

and it prints "Mo".

Is this behavior the same as in WPF where child controls inherit the data context of their parent view? And is it considered improper practice to use this in your application?

Thanks.

+4
source share
2 answers

Is this behavior the same as in WPF, where child controls inherit the data context of their parent view?

Yes.

I see that you are not transferring any model to. Will this work just to inherit the layouts and then not need to use partial at all?

If you want to continue to use it, just like you, you can probably just talk about it in more detail and pass on the current partial model.

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

Passing the model through htmlHelper.ViewData, you can access the model in the same way in your view using @ {ViewData.Model}, but this is NOT a good practice.

+4
source

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

 @Html.Partial("viewname", Model) 

Nothing wrong with this approach to IMO as a whole matters in the strongly typed representations and the benefits they bring ...

+1
source

Source: https://habr.com/ru/post/1446643/


All Articles