Asp.Net MVC C# 更新/编辑用户模型状态无效

大熊

我有一个简单的问题,我正在更新我的用户,那里的角色和我的 modelstate.isvalid 失败了。所以用户不会在数据库中得到更新。我没有任何 [必需] 没有输入到文本框中,即使我尝试输入所有字段,它仍然失败。不知道为什么。

这是我的数据模型,我用于编辑/更新用户和角色的控制器操作,还有我的视图,其中包含视图内部的所有控件。我真的不知道为什么我的模型状态无效我没有做任何复杂的事情它只是 CRUD 中的一个简单的 U 并且动作控制器没有验证模型。

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>
用户3543878

抱歉没有50个声望不能评论。

正如 Chetan 所说,调试并检查 ModelState 错误并检查 UserRoles 属性是否有问题。

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

Asp.Net MVC 5模型状态

来自分类Dev

发布不会更新部分[C#/ MVC / ASP.Net]

来自分类Dev

ASP.NET MVC复杂模型更新

来自分类Dev

更新,编辑,删除和导入文件。javascript。在Visual Studio中使用ASP:.NET MVC C#

来自分类Dev

在ASP.NET MVC C#中将OAuth与用户或人员模型连接

来自分类Dev

文件上传导致ASP.NET MVC中的模型状态无效

来自分类Dev

文件上传导致ASP.NET MVC中的模型状态无效

来自分类Dev

ASP .NET MVC 5 根据角色和/或状态编辑表单

来自分类Dev

编辑多个模型实例asp.net MVC

来自分类Dev

ASP.NET MVC 5模型绑定编辑视图

来自分类Dev

编辑模型的多个实例asp.net mvc

来自分类Dev

编辑用户删除密码 - ASP.NET MVC

来自分类Dev

ASP.NET MVC会话状态超时

来自分类Dev

ASP.NET MVC记录状态

来自分类Dev

ASP NET MVC 5会话状态

来自分类Dev

ASP.NET MVC视图模型呈现

来自分类Dev

ASP.NET MVC模型验证

来自分类Dev

ASP.NET MVC删除模型验证

来自分类Dev

Asp.net- Mvc复杂模型绑定

来自分类Dev

ASP.NET MVC视图模型呈现

来自分类Dev

ASP.NET MVC-获取用户的登录状态

来自分类Dev

LinqToTwitter用户授权ASP.NET MVC

来自分类Dev

ASP.NET MVC找不到用户

来自分类Dev

注销指定用户asp.net mvc

来自分类Dev

Asp.net MVC和用户

来自分类Dev

ASP.NET MVC找不到用户

来自分类Dev

LinqToTwitter用户授权ASP.NET MVC

来自分类Dev

ASP.NET MVC 用户使用

来自分类Dev

更新ASP .Net MVC中的记录