Model not passed to ASP.NET MVC 3

I have an index view where I got a form containing a partial view for different formulas.

@Html.ValidationSummary(true, "Beheben Sie die Fehler, und wiederholen Sie den Vorgang.") @using (Html.BeginForm()) { object mod = null; switch (Model.Step) { case 1: Html.RenderPartial("Step1", Model.Step1); break; case 2: Html.RenderPartial("Step2", Model.Step2); break; default: Html.RenderPartial("Step0"); break; } <p> @if (Model.Step > 100000) { <button name="button" value="Zurück" /> } @if (Model.Step != 0) { <input type="submit" name="submit" value="Zurück" /> <input type="submit" name="submit" value="Weiter" id="Weiter" /> <input type="submit" name="submit" value="Abbrechen" /> } </p> } 

In my controller, I got something like this:

 [HttpPost] public ActionResult Index(InputModel model, string submit, HttpPostedFileBase file) { if (String.IsNullOrEmpty(submit)) submit = ""; if (submit == "Weiter") model.Step++; if (submit == "Zurück") model.Step--; 

There are several submodules in InputModel:

 public Step1Model Step1 { get; set; } public Step2Model Step2 { get; set; } public Step3Model Step3 { get; set; } 

Which are transferred to a partial view to fill them. The problem is that I always get an empty model in my HttpPost in my controller. What am I doing wrong?

+4
source share
1 answer

What am I doing wrong?

You are using partial ones. Particles do not respect the navigation context. Therefore, when you look at your generated HTML source, you will see the following:

 <input type="text" name="SomeProperty" value="some value" /> 

instead of the correct one expected with a default binder:

 <input type="text" name="Step1.SomeProperty" value="some value" /> 

Therefore, when you submit this form, you are not properly attached to the Step1 property. The same remark for other complex properties.

One possibility is to use editor templates instead of partial ones, because they preserve the navigation context and generate their own names for your input fields.

So, instead of:

 Html.RenderPartial("Step1", Model.Step1); 

using:

 @Html.EditorFor(x => x.Step1, "Step1") 

and then move the partial ~/Views/SomeController/Step1.cshtml to ~/Views/SomeController/EditorTemlpates/Step1.cshtml .

If you do not want to use editor templates, but save them with partial ones, you can change the temlpate prefix inside the partial one. So, for example, inside Step1.cshtml partial, you can put the following at the top:

 @{ ViewData.TemplateInfo.HtmlFieldPrefix = "Step1"; } 

Now that you are checking your generated HTML source code, the names of your own sources should be selected for the input fields. Personally, I would recommend that you use the editor template approach to avoid hard coding of the prefix and make it partially less reusable compared to editor templates.

+7
source

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


All Articles