Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC 4. ModelState.IsValid always return true

I don't understand why ModelState.isValid give me in all the ways. I set something in the email returns true and I pùt empty field, it returns true too. My question ism, what do I have to do to return true when the field is empty and nothing whn I wrote the email?

I have the next view file:

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    <div style="padding-top:5px;clear:both;"></div>
    <% using (Html.BeginForm()) { %>
        <%: Html.ValidationSummary(true) %>   
        <fieldset>
                <legend>Email usuario</legend>

                <div class="editor-field">
                    <%: Html.TextBoxFor(m => m.Email) %>
                    <%: Html.ValidationMessageFor(m => m.Email) %>
                </div>

                <input type="submit" value="Enviar Email" />
        </fieldset>
    <% } %>
    <div style="padding-top:5px;clear:both;"></div>
</asp:Content>

The Controller is:

//
// GET: /Account/EmailRequest
public ActionResult EmailRequest()
{
    return View();
}

[HttpPost]
public ActionResult EmailRequest(string email)
{
    if (ModelState.IsValid)
    {
        // save to db, for instance
        return RedirectToAction("AnotherAction");
    }
    return View();
}

My model class is:

    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.Globalization;
    using System.Web.Mvc;
    using System.Web.Security;

namespace PortalClient.Models
{
    public class EmailRequest
    {

        [Required(ErrorMessage = "required")]
        public string Email { get; set; }
    }
}
like image 698
Dave Avatar asked Jul 01 '13 14:07

Dave


People also ask

Why ModelState IsValid is false in MVC?

That's because an error exists; ModelState. IsValid is false if any of the properties submitted have any error messages attached to them. What all of this means is that by setting up the validation in this manner, we allow MVC to just work the way it was designed.

What exactly does ModelState IsValid do?

ModelState. IsValid indicates if it was possible to bind the incoming values from the request to the model correctly and whether any explicitly specified validation rules were broken during the model binding process.


2 Answers

Change the signature of your post action from string email to EmailRequest model and then check the state. e.g.

[HttpPost]
public ActionResult EmailRequest(EmailRequest model)
{
    if (ModelState.IsValid)
    {
        // save to db, for instance
        return RedirectToAction("AnotherAction");
    }
    return View();
}
like image 147
George Johnston Avatar answered Nov 03 '22 01:11

George Johnston


You need to bind a view model to your view.

Change your EmailRequest model to something more descriptive like:

public class EmailRequestViewModel
{
     [Required(ErrorMessage = "Required")]
     public string Email { get; set; }
}

Your get action method would look something like:

public ActionResult EmailRequest()
{
     EmailRequestViewModel viewModel = new EmailRequestViewModel();

     return View(viewModel);
}

Your post action method:

public ActionResult EmailRequest(EmailRequestViewModel viewModel)
{
     // Check for null view model

     if (!ModelState.IsValid)
     {
          return View(viewModel);
     }

     // Do whatever you need to do

     return RedirectToAction("List");
}

And then your view. Please excuse the ASP.NET MVC 4 code, MVC 2 is prehistoric :) This is just part of your view:

@model YourProject.ViewModels.EmailRequestViewModel

@using (Html.BeginForm())
{
     @Html.TextBoxFor(x => x.Email)
     @Html.ValidationMessageFor(x => x.Email)
}

I hope this helps.

like image 39
Brendan Vogt Avatar answered Nov 03 '22 01:11

Brendan Vogt