ASP.Net MVC 2: Using viewmodel breaks my model binding

I assume this is a story about how frameworks fun 95% of what you need, but then frowned disapprovingly at the last five percent; let us know that if you want to participate in non-standard Malacca, this is your own business, thank you very much, and he will be here if you decide that you want to return to what you are doing well. Generally speaking, it is inevitable that the last five percent will contain some version of the required function.

I have a strongly typed view that updates a data object. I used the idiomatic helpers of MVC2, for example Html.TextBoxFor(model = > model.Name). I used editor templates for nested objects. (My backend is a collection of Mongolian documents, so I need to represent complex types).

Then I need a dropdown menu. Turns out drop-down lists are a bit mediocre; no problem, I will do a viewmodel instead of directly accessing item:

class itemViewModel
{
    ...
    public Item item { get; set; }
    public IEnumerable<SelectListItem> dropdown { get; set; }
}

public ActionResult()
{
    return View("Update", new itemViewModel(item, dropdown))
}

... which works fine, the popup menu populates. But! my view needs to be updated:

Html.TextBoxFor(model => model.Name) ->
Html.TextBoxFor(model => model.item.Name)

Great, the problem is resolved. Unfortunately, now my binding to the model does not work. I am debugging and looking at the values Request.Form: Oh. item.Nameinstead of Name. Has the meaning. I will say that in my updated view it is expected itemViewModel, and the binding works.

, , . , . , , , , viewmodel. Address.City item.Address.City, .

:

  • , item,
  • viewmodel ViewData
  • HtmlHelpers
  • HtmlHelper, lamba .
  • / .

, . Viewmodels , . , ? # ( , , , , CS, , , ). ; . , , , . , .

+3
2

. Googling , , , Bind:

[HttpPost]
public ActionResult([Bind(Prefix="item")] item)
{
    //item complex types populate correctly
}

, .

, - n00b , .

+8

, -, , .NET, # ASP.NET MVC . , , . .

, ASP.NET MVC ( ASP.NET MVC Framework Design), . , , :

, -, , . , , , . , , , : "" /, , , , . ? , () .

-9

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


All Articles