2

This is a follow up to MVC3 form in partial view

Although the author gave a workaround to the problem. I would like to find out a proper answer why this is not working.

I don't have access to original code, but here's mine (so I can answer following questions):

// main view (which is partial too)
    @foreach (AddingComponentVM sc in Model)
    {
        @Html.Partial("_SearchIngredientUpdate", sc);     
    }

//partial view
@using (Ajax.BeginForm("IngredientSearchUpdate", new { controller = "Recipe" }, ajxOpt, new { id = "addingWidgetForm" + Model.IngredientID }))
    {           
        @Html.TextBoxFor(model => model.IngredientID)
        @Model.IngredientID
    }

@Model.IngredientID contains proper value. But the textbox contains value of the model sent to controller (sic!) and it is obviously the same for each form.

[AjaxOnly]
public JsonResult IngredientSearchUpdate(
    AddingComponentVM dataIn,
    [ModelBinder(typeof(SearchOptionsBinder))] SearchOptions sessionSO)

If action without AddingComponentVM in signature calls the same code above, forms renders correctly.

public PartialViewResult IngredientSearch([ModelBinder(typeof(SearchOptionsBinder))] SearchOptions sessionSO)

Anyone could point me out to the cause of this strange (at least for me) behaviour? Thanks!

Community
  • 1
  • 1
Mariusz.W
  • 1,347
  • 12
  • 19
  • 1
    I prefer using EditorTemplates to render these kind of forms, rather than Partial views. Partials tend to act sometimes strangely (though if you know how it works, it is logical) and have unexpected behaviour. – Styxxy Aug 03 '12 at 15:03
  • 1
    Very good and interesting suggestion. I still would like to know why it does work they way it works! Thanks – Mariusz.W Aug 03 '12 at 15:13
  • I implemented that with EditorTemplates and exactly the same things happen. There is a clash with data sent with POST. Apparently that's how TextBoxFor (etc) work. They search for values first in ViewData, ViewBag and then in model. Still need help with that. – Mariusz.W Aug 04 '12 at 22:16

1 Answers1

2

I couldn't sleep because of this, but here's the answer:

It does not matter whether you use PartialView or EditorTemplates. As described here: How to modify posted form data within controller action before sending to view?

"HTML Helpers uses the following order precedence when attempting lookup of the key:

  1. ViewData.ModelState dictionary entry
  2. Model property (if a strongly typed view. This property is a shortcut to View.ViewData.Model)
  3. ViewData dictionary entry"

So if any values were posted it is enough to clear StateModel collection and then the data from model can be pick up by html helper used. This will do the trick:

ModelState.Clear()
Community
  • 1
  • 1
Mariusz.W
  • 1,347
  • 12
  • 19