开发者

How do I keep field values in the ASP.NET MVC form if it has been invalidated?

I have a form that is going through some validation before sending an e-mail.

I have tried using this for validation, where the method ValidateInput sets the ModelState depending on the input:

[HttpPost]
public ActionResult Creat开发者_如何学Goe(FormCollection collection)
{
    ValidateInput(collection);
    if (ModelState.IsValid == false) return View(collection);

This clears all the entered fields if something is invalid. I want to keep all the entered data in the field. How can I do that?


Are you using Html helpers for input field in your form or regular html tags?

<%: Html.TextBoxFor(x => x.Message) %> - original value will be kept
<input type="text" name="Message" /> - original value will be lost after postback

Also you could benefit from using build-in validation (with data annotation attributes) instead of using your own validation method.


AFAIK you wouldn't need to call ValidateInput yourself in the Create method - the framework has already set ModelState for you, so just remove the first line.


If you can't change the ValidateInput method to not wipe your properties in this scenario then you'll really need two copies of the form data, one to pass to this method and one in reserve to pass to the view if validation fails.
You may be better off using a specific view model for the actions view rather than relying on the FormCollection object. That way you can use model binding to retrieve the data.
I think the code below should work but I haven't had a chance to test it so beware!

[HttpPost]
public ActionResult Create(MyCreateViewModel collection)
{
    MyCreateViewModel myCVM = new MyCreateViewModel();
    TryUpdateModel(myCVM);
    ValidateInput(myCVM);
    if (ModelState.IsValid == false) return View(collection);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜