Controllers:
public ActionResult EditTest()
{
return View(new EditTestViewModel("Is this a test?"));
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult EditTest(EditTestViewModel test)
{
return View(new EditTestViewModel("Is this a test?"));
}
ViewModel:
public class EditTestViewModel
{
public String test { get; set; }
public EditTestViewModel(String test)
{
this.test = test;
}
}
View:
<% using (Html.BeginForm("EditTest", "Test", FormMethod.Post)) {%>
<%= Html.ValidationSummary(true) %>
<%= Html.TextBoxFor(model => model.test) %>
<%= Html.ValidationMessageFor(model => model.test) %>
<input type="submit" value="Save" />
<% } %>
Result when I click save (whether I edit the data or not):
The value “Is this a test?” is
invalid.
What is going on?
The first exception you will get when you run this code and submit the form is the following:
That’s because
EditTestViewModeldoesn’t have a parameterless constructor you cannot use it like this.The second problem with your code is that you are creating a new object in your POST action instead of reusing the one that’s being passed as argument.
So here’s how to fix:
View model:
Controller:
And if for some reason you wanted to edit the value in the POST action and this to reflect in the view you will need to remove it from the model state or the HTML helpers will pick the old value: