0

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.

Here is my data model, my controller action for editing / updating a user and there role and also here is my view with all the controls for inside the view. Im realy not sure why my modelstate isnt valid i'm not doing anything complicated its just a simple U in CRUD and the action controller isnt validiting the model.

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; }
    }
public async Task<ActionResult> EditSuperAdmin(string id)
        {
            if(id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            var store = new UserStore<ApplicationUser>(context);
            var manager = new UserManager<ApplicationUser>(store);
            var user = await manager.FindByIdAsync(id);
            if(user == null)
            {
                return HttpNotFound();
            }
            var userRoles = await manager.GetRolesAsync(user.Id);

            ViewBag.Roles = new SelectList(
                context.Roles.ToList(), "Name", "Name");
                //new SelectList(context.Roles.Where(u =>
               //!u.Name.Contains("SuperAdmin")).ToList(), "Name", "Name");

            return View(new UpdateUserViewModel()
            {
                UserId = user.Id,
                IdShortened = user.Id.Substring(0, 10),
                Email = user.Email,
                UserName = user.UserName,
                Name = user.Name,
                PhoneNumber = user.PhoneNumber,
                Birthday = user.Birthday,
                DateCreated = user.DateCreated,
                UserRoles = manager.GetRoles(user.Id).FirstOrDefault()
            });
        }
        [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);
                if (user == null)
                {
                    return HttpNotFound();
                }
                user.Email = model.Email;
                user.UserName = model.UserName;
                user.Name = model.Name;
                user.PhoneNumber = model.PhoneNumber;
                user.Birthday = model.Birthday;
                user.DateCreated = Convert.ToDateTime(model.DateCreated);
                var roleResult =
                    manager.AddToRole(user.Id, model.UserRoles);
                if (!roleResult.Succeeded)
                {
                    TempData["ErrorRole"] = "Error adding User Role";
                    return RedirectToAction("Dashboard");
                }
                manager.Update(user);
                context.SaveChanges();                
                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">
        <div class="text-center">
            @if (User.IsInRole("SuperAdmin"))
            {
                <h2>Update Super Administrator</h2>
            }
            else
            {
                <h3>Update | Edit User Account</h3>
            }
        </div>
        <hr />
        @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>
Bigbear
  • 489
  • 2
  • 5
  • 21
  • You need to debug your code and check `ModeState.Errors` property – Chetan Apr 05 '19 at 00:32
  • There is no ModelState.Error or ModelState.Errors I looked throughout and I even added it as a watch variable and its nowhere to be found. I checked every property on my modelstate and it doesnt say anywhere that its failing or throwing an exception. I checked every key and value... I am very confused why its failing I even tried 'ModelState.Remove("Birthday");' on a bunch of properties and still fails.. – Bigbear Apr 06 '19 at 00:11
  • Try to find out which errors make the `IsValid` property set to false by following this post: https://stackoverflow.com/questions/1791570/modelstate-isvalid-false-why. If you could get them, edit your question as additional info. – Tetsuya Yamamoto Apr 09 '19 at 02:21

2 Answers2

0

Sorry don't have 50 reputations can't comment.

As Chetan said debug and check the ModelState errors and check if UserRoles property is the issue.

user3543878
  • 167
  • 1
  • 2
  • 11
0

it will be fine if you go with entity framework. Everything works fine there.