Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 603
user2026343 Avatar asked Dec 29 '25 22:12

user2026343


1 Answers

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.

like image 82
StuartLC Avatar answered Jan 01 '26 11:01

StuartLC