MVC-Post page partially - model binding failure

I am trying to post a part of a page and bind it to view a model on a 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 in the textbox testText

and hit submit, I reach the Search action, but vm.TestText

empty, I cannot bind the form field from the editor template to the view model. Any ideas?

+3


source to share


1 answer


This is because the class passed to both @model

your view wraps the class SearchVM

, and when called, @Html.EditorFor(model => model.SearchVM)

it displays the input prefixed with SearchVM

:

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

      

In turn, when sent back to the controller will ModelBinder

not be able to deserialize this intoSearchVM



What you can do is use thisEditorFor

overload:

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

      

Where _SearchVM

is the name of your editor template. Passing ""

as a parameter htmlFieldName

will remove the unwanted prefix SearchVM

from the input.

+4


source







All Articles