Eedoh
Eedoh

Reputation: 6278

ASP.NET MVC validation in weakly typed views

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)?

Upvotes: 0

Views: 1487

Answers (1)

Adeel
Adeel

Reputation: 19228

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.") %>

Upvotes: 2

Related Questions