views:

40

answers:

1

Hello.

I have a problem validating data on view that is not strongly typed. I'm updating data from 3 different models on that view, and I have validation methods that work on them, but I don't know how to display the validation message.

Where should I put validation messages (for strongly typed views I put them in ModelState, I presume that does not make sense in this case), and how should I display them (I doubt that I will be able to use "validationmessagefor", maybe "validationmessage" somehow)?

A: 

Using Asp.net MVC validation is very easy in strongly typed but if you have a view that is not strongly typed, you can still do it easily. Suppose you have following action in controller.

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Login(string userEmail, string password)
{
    if (ValidateLogin(userEmail, password))
    {
                //redirect
    }
    return View();
}

and your validation method looks like,

private bool ValidateLogin(string userEmail, string password)
{
    if (String.IsNullOrEmpty(userEmail))
    {
        ModelState.AddModelError("username", "You must specify a username.");
    }


    if (password == null || password.Length == 0)
    {
        ModelState.AddModelError("password",
               String.Format(CultureInfo.CurrentCulture,
               "You must specify a password."));
    }

    return ModelState.IsValid;
 }

Now in your view, in this case login.aspx in your views folder, you can show your validation in this way.

<label for="useremail">User Email:</label>
<%= Html.TextBox("useremail") %>
<%= Html.ValidationMessage("useremail")%>

Beside this, you can also show validation summary or just show a generic method by using the following helper method.

<%= Html.ValidationSummary(true, "Please correct the errors.") %>
Adeel
Well, this is how I did it (first method, without validation summary). I debugged and noticed that validation message is added to the modelstate, but I don't get that message on my view :S. I must be doing something wrong, but dunno what :S.
Eedoh