[Solved] ModelState.IsValid is always returning false in ASP.Net MVC

Last Reply on Apr 08, 2019 01:52 AM By dharmendr

Posted on Apr 04, 2019 06:08 PM

I have a quick question I am updating my user and there role and my modelstate.isvalid is failing.

So the user does not get updated in the database. I don’t have anything [required] that isn't being entered in a textbox even when I try to enter all fields it still fails. Not sure why.

    public class UpdateUserViewModel
    {
        public string UserId { get; set; }
        [Display(Name = "User ID")]
        public string IdShortened { get; set; }
        [Required]
        [EmailAddress]
        [Display(Name = "Email")]
        public string Email { get; set; }
        [Required]
        [Display(Name = "Username")]
        public string UserName { get; set; }
        [Display(Name = "Your Name")]
        public string Name { get; set; }
        [Display(Name = "Phone Number")]
        public string PhoneNumber { get; set; }
        [DataType(DataType.DateTime), DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
        [Display(Name = "Birthday")]
        public DateTime Birthday { get; set; }
        [Display(Name = "Date Created")]
        public DateTime? DateCreated { get; set; }
        [Required]
        [Display(Name = "User Roles")]
        public string UserRoles { get; set; }
    }

 

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult EditSuperAdmin([Bind]UpdateUserViewModel model)
        {
            var store = new UserStore<ApplicationUser>(context);
            var manager = new UserManager<ApplicationUser>(store);

            if (ModelState.IsValid)
            {
                var user = manager.FindById(model.UserId);                                
                TempData["Success"] = "User Updated Successfully";              
                return RedirectToAction("GetAllUsers", "SuperAdmin");
            }
            TempData["Error"] = "User Update Failed";
            return RedirectToAction("Dashboard");
        }

 

@model MVC_TimeSh.Models.UpdateUserViewModel

@{
    ViewData["Title"] = "Update User";
}

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        @Html.HiddenFor(m => m.UserId)

        <div class="form-group">
            @Html.LabelFor(model => model.IdShortened,
             htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.IdShortened, new { htmlAttributes =
                 new { @class = "form-control", @readonly = "readonly" } })
                @Html.ValidationMessageFor(model => model.IdShortened, "",
                 new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Name,
             htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Name,
                 new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Name, "",
                 new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Email,
             htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Email, new { htmlAttributes =
                 new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Email, "",
                 new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.UserName,
             htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.UserName,
                 new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.UserName, "",
                 new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.PhoneNumber,
             htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.PhoneNumber,
                 new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.PhoneNumber, "",
                 new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Birthday,
             htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Birthday,
                 new { htmlAttributes = new { @class = "form-control datepicker" } })
                @Html.ValidationMessageFor(model => model.Birthday, "",
                 new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.DateCreated,
             htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.DateCreated, new { htmlAttributes =
                 new { @class = "form-control", @readonly = "readonly" } })
                @Html.ValidationMessageFor(model => model.DateCreated, "",
                 new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.UserRoles,
             htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownList("UserRoles", (SelectList)ViewBag.Roles, "-- SELECT --")
                @*new { htmlAttributes = new { @class = "form-control" } })*@

                @Html.ValidationMessageFor(model => model.UserRoles, "",
                 new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Save" class="btn btn-success" />
            </div>
        </div>
    </div>

 

You are viewing reply posted by: dharmendr on Apr 08, 2019 01:52 AM.
Posted on Apr 08, 2019 01:52 AM

Hi bigbear,

Check this example. Now please take its reference and correct your code.

Namespaces

using System.ComponentModel;
using System.ComponentModel.DataAnnotations;

Model

public class UpdateUserViewModel
{
    public string UserId { get; set; }
    [DisplayName("User ID")]
    public string IdShortened { get; set; }
    [Required]
    [DisplayName("Email")]
    public string Email { get; set; }
    [Required]
    [DisplayName("Username")]
    public string UserName { get; set; }
    [DisplayName("Your Name")]
    public string Name { get; set; }
    [DisplayName("Phone Number")]
    public string PhoneNumber { get; set; }
    [DataType(DataType.DateTime), DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
    [DisplayName("Birthday")]
    public DateTime? Birthday { get; set; }
    [DisplayName("Date Created")]
    public DateTime? DateCreated { get; set; }
    [Required]
    [DisplayName("User Roles")]
    public string UserRoles { get; set; }
}

Controller

public class HomeController : Controller
{
    // GET: /Home/
    public ActionResult Index()
    {
        List<SelectListItem> lstAdmins = new List<SelectListItem>();
        lstAdmins.Add(new SelectListItem { Value = "1", Text = "Admin 1" });
        lstAdmins.Add(new SelectListItem { Value = "2", Text = "Admin 2" });
        lstAdmins.Add(new SelectListItem { Value = "3", Text = "Admin 3" });
        TempData["Roles"] = lstAdmins;
        return View();
    }
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult EditSuperAdmin([Bind]UpdateUserViewModel model)
    {
        if (ModelState.IsValid)
        {
            TempData["Success"] = "User Updated Successfully";
            //return RedirectToAction("Index", "Home");
        }
        else
        {
            TempData["Error"] = "User Update Failed ! <br/>Please fill the required Fields.";
            //return RedirectToAction("Index");
        }

        List<SelectListItem> lstAdmins = new List<SelectListItem>();
        lstAdmins.Add(new SelectListItem { Value = "1", Text = "Admin 1" });
        lstAdmins.Add(new SelectListItem { Value = "2", Text = "Admin 2" });
        lstAdmins.Add(new SelectListItem { Value = "3", Text = "Admin 3" });
        TempData["Roles"] = lstAdmins;

        return View("Index");
    }
}

View

<div>
    <%using (Html.BeginForm("EditSuperAdmin", "Home", FormMethod.Post)) {%>
    <%:Html.AntiForgeryToken() %>
    <div class="form-horizontal">
        <div class="text-center">
            <%:Html.ValidationSummary(true, "", new { @class = "text-danger" })%>
            <%:Html.HiddenFor(m => m.UserId)%>
            <div class="form-group">
                <%:Html.LabelFor(model => model.IdShortened)%>
                <div class="col-md-10">
                    <%:Html.EditorFor(model => model.IdShortened, new { htmlAttributes = new { @class = "form-control", @readonly = "readonly" } })%>
                    <%:Html.ValidationMessageFor(model => model.IdShortened, "", new { @class = "text-danger" })%>
                </div>
            </div>
            <div class="form-group">
                <%:Html.LabelFor(model => model.Name)%>
                <div class="col-md-10">
                    <%:Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control"} }) %>
                    <%:Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger"                        })%>
                </div>
            </div>
            <div class="form-group">
                <%:Html.LabelFor(model => model.Email)%>
                <div class="col-md-10">
                    <%:Html.EditorFor(model => model.Email, new { htmlAttributes = new { @class = "form-control" } })%>
                    <%:Html.ValidationMessageFor(model => model.Email, "", new { @class = "text-danger" })%>
                </div>
            </div>
            <div class="form-group">
                <%:Html.LabelFor(model => model.UserName)%>
                <div class="col-md-10">
                    <%:Html.EditorFor(model => model.UserName, new { htmlAttributes = new { @class = "form-control" } })%>
                    <%:Html.ValidationMessageFor(model => model.UserName, "", new { @class = "text-danger" })%>
                </div>
            </div>
            <div class="form-group">
                <%:Html.LabelFor(model => model.PhoneNumber)%>
                <div class="col-md-10">
                    <%:Html.EditorFor(model => model.PhoneNumber, new { htmlAttributes = new { @class = "form-control" } }) %>
                    <%:Html.ValidationMessageFor(model => model.PhoneNumber, "", new { @class = "text-danger" })%>
                </div>
            </div>
            <div class="form-group">
                <%:Html.LabelFor(model => model.Birthday)%>
                <div class="col-md-10">
                    <%:Html.EditorFor(model => model.Birthday, new { htmlAttributes = new { @class = "form-control datepicker" } }) %>
                    <%:Html.ValidationMessageFor(model => model.Birthday, "", new { @class = "text-danger" })%>
                </div>
            </div>
            <div class="form-group">
                <%:Html.LabelFor(model => model.DateCreated)%>
                <div class="col-md-10">
                    <%:Html.EditorFor(model => model.DateCreated, new { htmlAttributes = new { @class = "form-control", @readonly = "readonly" } }) %>
                    <%:Html.ValidationMessageFor(model => model.DateCreated, "", new { @class = "text-danger" })%>
                </div>
            </div>
            <div class="form-group">
                <%:Html.LabelFor(model => model.UserRoles)%>
                <div class="col-md-10">
                    <%:Html.DropDownList("UserRoles", (IEnumerable<SelectListItem>)TempData["Roles"], "-- SELECT --", new { htmlAttributes = new { @class = "form-control" } })%>
                    <%:Html.ValidationMessageFor(model=> model.UserRoles, "", new { @class = "text-danger" })%>
                </div>
            </div>
            <div class="form-group">
                <div class="col-md-offset-2 col-md-10">
                    <input type="submit" value="Save" class="btn btn-success" />
                </div>
            </div>
            <%if (TempData["Success"] != null) {%>
            <span><%=TempData["Success"] %></span>
            <% } %>
            <br />
            <%if (TempData["Error"] != null) {%>
            <span><%=TempData["Error"]%></span>
            <% } %>
        </div>
    </div>
    <%} %>
</div>

Screenshot