MVC 4. ModelState.IsValid always return true
Asked Answered
N

3

7

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; }
    }
}
Noellenoellyn answered 1/7, 2013 at 14:12 Comment(6)
If you change the signature of your post action from string email to EmailRequest model and then check the state, what result do you see?Bettencourt
[HttpPost] public ActionResult EmailRequest(EmailRequest email) { if (ModelState.IsValid) { // save to db, for instance return RedirectToAction("AnotherAction"); } return View(); }Noellenoellyn
The function as you suggested me I changed from string to EmailRequest and it returns nullNoellenoellyn
Ok I got the solution for the last comment, I had to add Model in EmailRequest. Now it is working. Thanks.Noellenoellyn
I added my comment as the solution, if it solved your issue.Bettencourt
@Noellenoellyn Hi and welcome to SO. To promote users for their effort treating your posts and answering your questions, please vote them up and mark them as answer.Fullblooded
B
7

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();
}
Bettencourt answered 1/7, 2013 at 16:1 Comment(1)
From far in the future, thanks for this answer. Solved my conundrum neatly.Tjirebon
P
3

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.

Pergrim answered 2/7, 2013 at 9:34 Comment(0)
N
-1

you need to bind your model with binder first to have ability to chek it by Modelstat.IsValid

    public ActionResult EmailRequest()
    {
           EmailRequest email = new EmailRequest();
           TryUpdateModel(email);
        if (ModelState.IsValid)
        {
            // save to db, for instance
            return RedirectToAction("AnotherAction");
        }
        return View();
    }
Negation answered 8/8, 2014 at 9:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.