MVC3 - Drop The RenderPartial Model

I have a page in MVC3 with the model "pageModel".

On this page I:

@{ Html.RenderPartial("_subPage", Model.subModel); } (Pagemodel.submodel) 

In my controller, I do:

  [Authorize] [AcceptVerbs(HttpVerbs.Post)] public ActionResult Results(pagemodel model, string frmAction) { } 

The page loads for the first time, but when I return the httpPost action httpPost , model.submodel always null.

My question is: how do I return an updated model from RenderPartial (if at all). I can get my model in partial, but not back!

+4
source share
3 answers

Partial problems are that they do not preserve the navigation context. This means that any input fields that you could place inside this partial will have incorrect names, and the default mediator will not be able to return values โ€‹โ€‹during POST. Your HTML will look like this:

 <input type="text" name="Prop1" value="property 1 value" /> <input type="text" name="Prop2" value="property 2 value" /> 

whereas correct:

 <input type="text" name="subModel.Prop1" value="property 1 value" /> <input type="text" name="subModel.Prop2" value="property 2 value" /> 

To achieve this correct markup, I would recommend that you use editor templates.

So you are replacing:

 @{ Html.RenderPartial("_subPage", Model.subModel); } 

from:

 @Html.EditorFor(x => x.subModel) 

and then you move the partial _subPage.cshtml to ~/Views/Shared/EditorTemplates/SubModelType.cshtml , where SubModelType is the type of the subModel property:

 @model SubModelType @Html.EditorFor(x => x.Prop1) @Html.EditorFor(x => x.Prop2) 

Now, when you look at the generated HTML, the corresponding input field names must be prefixed with subModel and inside the POST controller action the model.subModel property this time will be correctly initialized and filled out from the values โ€‹โ€‹entered by the user in the input fields.

+12
source

you will need to change the partial view to accept a top-level model, for example:

 @{ Html.RenderPartial("_subPage", Model); } 

which will then display your properties in a partial view with the correct property names, i.e.:

<input type="text" name="subModel.MyProperty" value="somevalue" />

It also means that your returned model in HttpPost action HttpPost need to fix the navigation relationship.

this is just one of those caveats related to viewmodels and hierarchies. Oh, by the way, in mvc3 you do not need detailed [AcceptVerbs(HttpVerbs.Post)] for messages. You can just use [HttpPost]

+1
source

You can also do the following.

 @Html.RenderPartial( "_subPage", Model.subModel, new ViewDataDictionary { TemplateInfo = new TemplateInfo { HtmlFieldPrefix = "subModel" } }); 

Your partial view will remain as it is using @model SubModel

+1
source

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


All Articles