views:

205

answers:

2

When I validate a form with Asp.Net Mvc and there's an error on the form, Asp.Net return me the form with the correct error message but clear the content of the input. I would like the content of the input to stay even if this content is wrong. How can I do that ?

UPDATE

Maybe this is because I don't use the default validation. I use the Fluent Validation library.

Here what I do :

var validator = new UserValidator();
var results = validator.Validate(user);
results.AddToModelState(ModelState, "");

if (!ModelState.IsValid) 
{
     return View("SignUp", user);
}
+2  A: 

The problem might be in how you "bind" the model you are passing in the view. If you use a strongly typed view and create the input fields with for example

<%=Html.TexboxFor(m=>m.UserName)%> 

or

<%=Html.TextBox("UserName", Model.UserName)%>

then you should see the values after posting. Regards

uvita
Your right. The problem was that I was setting a default value to my textbox instead of using Model.UserName. How can I use Model.UserName and also set a default value ?
Melursus
I recommend you to pass the model to the View in the initial request and put whatever default value you want in it (either in the constructor of the model or by setting the property values). In this way the view will remain very simple and you can use the same view for creation and edition of the same entity.
uvita
A: 

In addition to what @Germán Ubillos posted, you can also store the post values in TempData and send them back through.

<%=Html.TextBox("UserName", TempData["UserName"])%>

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult SomeAction(string UserName)
    {
        TempData["UserName"] = UserName;

        // Do your validation
        var validator = new UserValidator();
        var results = validator.Validate(user);
        results.AddToModelState(ModelState, "");

        if (!ModelState.IsValid) 
        {
            return View("SignUp", user);
        }
        //return some view
    }
Coov