【问题标题】:modelstate.isvalid return false in edit view only using asp.net mvc4modelstate.isvalid 仅使用 asp.net mvc4 在编辑视图中返回 false
【发布时间】:2016-01-02 23:23:48
【问题描述】:

我是 asp.net mvc 的新手,我想知道为什么 ModelState.IsValid=false ? 使用时在编辑视图中

 if (ModelState.IsValid)
                {
                  //code
                }

此处列出的完整代码: 模型类:

  public class Departments
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public virtual ICollection<Employee> Employeesss { get; set; }


public class Employee
    {
        public int EmployeeId { get; set; }
        public string Name { get; set; }
        public string City { get; set; }
        public int DepartmentId { get; set; }

        [ForeignKey("DepartmentId")]
        public virtual Departments Id { get; set; }
    }


public class dropdownDbContext : DbContext
    {
        public DbSet<Departments> Departments { get; set; }

        public DbSet<Employee> Employees { get; set; }

    }

在控制器中,这些是编辑控制器

 public ActionResult Edit(int id = 0)
        {
            Employee employee = db.Employees.Find(id);
            if (employee == null)
            {
                return HttpNotFound();
            }
            ViewBag.DepartmentId = new SelectList(db.Departments, "Id", "Name", employee.DepartmentId);
            return View(employee);
        }

        //
        // POST: /empttttttttttttttttt/Edit/5

        [HttpPost]
        public ActionResult Edit(Employee employee)
        {
            if (!ModelState.IsValid)
            {
                var errors = ModelState.SelectMany(x => x.Value.Errors.Select(z => z.Exception));

                // Breakpoint, Log or examine the list with Exceptions.
            }

            if (ModelState.IsValid)
            {
                db.Entry(employee).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            ViewBag.DepartmentId = new SelectList(db.Departments, "Id", "Name", employee.DepartmentId);
            return View(employee);
        }

在视图中

@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>Employee</legend>

        @Html.HiddenFor(model => model.EmployeeId)

        <div class="editor-label">
            @Html.LabelFor(model => model.Name)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Name)
            @Html.ValidationMessageFor(model => model.Name)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.City)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.City)
            @Html.ValidationMessageFor(model => model.City)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.DepartmentId, "Id")
        </div>
        <div class="editor-field">
            @Html.DropDownList("DepartmentId", String.Empty)
            @Html.ValidationMessageFor(model => model.DepartmentId)
        </div>

        <p>
            <input type="submit" value="Save" />
        </p>
    </fieldset>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

它没有显示错误,但在使用此逻辑时编辑无法正常工作

  if (ModelState.IsValid)
                {
                    db.Entry(employee).State = EntityState.Modified;
                    db.SaveChanges();
                    return RedirectToAction("Index");
                }

我想知道为什么 ModelState.IsValid=false ??

这是错误快照

The parameter conversion from type 'System.String' to type 'dropdown.Models.Departments' failed because no type converter can convert between these types.

【问题讨论】:

    标签: c# asp.net asp.net-mvc asp.net-mvc-4


    【解决方案1】:

    变化:

    if (!ModelState.IsValid)
    {
         var errors = ModelState.SelectMany(x => x.Value.Errors.Select(z => z.Exception));
        // Breakpoint, Log or examine the list with Exceptions.
    }
    

    收件人:

    if (!ModelState.IsValid)
    {
        var errors = ModelState
        .Where(x => x.Value.Errors.Count > 0)
        .Select(x => new { x.Key, x.Value.Errors })
        .ToArray();
    }
    

    然后你将断点放在错误上


    编辑:

    像这样改变你的模型:

    public class Employee
    {
        public int EmployeeId { get; set; }
        public string Name { get; set; }
        public string City { get; set; }
    
        [ForeignKey("Departments")]
        public int DepartmentId { get; set; }
        public virtual Departments department { get; set; }
    }
    

    【讨论】:

    • 错误消息是从类型“System.String”到类型“dropdown.Models.Departments”的参数转换失败,因为没有类型转换器可以在这些类型之间进行转换。对于关键“Id”,我认为这是因为两个类之间的关系应该以不同的方式处理
    • 谢谢,当我更改公共虚拟部门 ID { get; 时效果很好放; } 到公共虚拟部门离开 { 得到;放;只需更改“Id”,也许这与某事发生冲突,我真的直到现在我才明白为什么 - 如果你有更多解释,这会很好
    • 这是因为您的 Id 变量类型为部门,并且您的外键属性设置不正确。
    猜你喜欢
    • 2011-02-22
    • 1970-01-01
    • 2018-02-16
    • 2013-09-08
    • 2020-04-11
    • 1970-01-01
    • 2019-09-11
    • 2017-08-12
    • 2022-12-18
    相关资源
    最近更新 更多