Search code examples
c#asp.net-mvcrazormodel-bindingmvc-editor-templates

MVC-Post Page Partially - Model Binding Fails


I am trying to post a part of the page and bind it to view model on the controller. My editor template for SearchVM :

@Html.TextBoxFor(model => model.TestText, new { @class = "form-control ",
                 @placeholder = "TEXT" , @id="test" })
<input type="submit" value="Submit" />

Index.cshtml:

@using (Html.BeginForm("Search", "Pencil", FormMethod.Post, 
                       new { enctype = "multipart/form-data" }))
{
   @Html.EditorFor(model => model.SearchVM);
}

Controller :

  public ActionResult Search(SearchVM vm)
  {
     // ...
  }

When I type something on the testText text box and hit submit, I reach the action Search but vm.TestText is empty, I can not bind the form field from editor template to the view model. Any idea?


Solution

  • This is happening because the class passed as the @model to your view wraps the SearchVM class, and when you call @Html.EditorFor(model => model.SearchVM) it renders the input with a prefix SearchVM:

    <input id="SearchVM_TestText" name="SearchVM.TestText" value="" ... />
    

    In turn, when posted back to the controller, the ModelBinder will fail to deserialize this into a SearchVM

    What you can do is use this EditorFor overload:

    @Html.EditorFor(model => model.SearchVM, "_SearchVM", "");
    

    Where _SearchVM is the name of your Editor template. Passing "" as the htmlFieldName parameter will remove the unwanted SearchVM prefix on the input.