Controllers:
public ActionResult EditTest()
{
return View(new EditTestView开发者_StackOverflowModel("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:
[MissingMethodException: No parameterless constructor defined for this object.]
That's because EditTestViewModel
doesn'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:
public class EditTestViewModel
{
public String test { get; set; }
}
Controller:
public ActionResult EditTest()
{
var model = new EditTestViewModel
{
test = "Is this a test?"
}
return View(model);
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult EditTest(EditTestViewModel test)
{
return View(model);
}
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:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult EditTest(EditTestViewModel test)
{
model.test = "new value";
ModelState.Remove("test");
return View(model);
}
精彩评论