Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 shouldn't even be passing a model to a view that's inded for another view, but I've noticed that the partial view is actually inheriting the Model from the parenmt View:

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 this Prints "Mo".

Is this behaviour intended like that in WPF where child controls inherit the data context of their parent View? And is it considered bad practise to use this in your application?

Thanks.

like image 719
Mohammad Sepahvand Avatar asked Nov 17 '12 13:11

Mohammad Sepahvand


People also ask

Can a partial view have its own model?

RenderAction method is used when some information is need to show on multiple pages. Hence partial view should have its own model.

What is true about partial view in MVC?

A partial view is a Razor markup file ( . cshtml ) without an @page directive that renders HTML output within another markup file's rendered output. The term partial view is used when developing either an MVC app, where markup files are called views, or a Razor Pages app, where markup files are called pages.

What is advantage of partial view in MVC?

Advantages of Partial View in ASP.net MVC:Enhances reusability by packaging up common website code instead of repeating the same in different pages. Easy to maintain. Changes in future are simple to accommodate.

What is difference between view and partial view in MVC?

Views are the general result of a page that results in a display. It's the highest level container except the masterpage. While a partial view is for a small piece of content that may be reused on different pages, or multiple times in a page.


1 Answers

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.

like image 61
slipsec Avatar answered Sep 25 '22 20:09

slipsec