ModelState.IsValid =假。关闭内部模型验证

时间:2017-10-22 23:49:55

标签: c# asp.net-mvc

我在使用EF6的Asp.Net MVC项目中使用JQueryUIHelpers的自动完成功能。

模型结构:

public class Employee
{
    [Key]
    public int Id { get; set; }
    [Required]
    public string FirstName { get; set; }
    [Required]
    public string SecondName { get; set; }
    [NotMapped]
    public string FullName => FirstName + " " + SecondName;
    public bool IsDriver { get; set; } = false;
    public virtual ICollection<Delivery> Deliveries { get; set; }
}
public class Delivery
{
    [Key]
    public int Id { get; set; }
    [Required]
    public Employee Driver { get; set; }
    public virtual ICollection<EggsMag> Eggs { get; set; }
}

EmployeeController:

public ActionResult Drivers(string term)
{
    var drivers = _rep.GetAll(e => e.IsDriver && (e.FirstName.StartsWith(term) || e.SecondName.StartsWith(term)));
    return Json((from d in drivers select new { label = d.FullName, value = d.Id }).ToList(), JsonRequestBehavior.AllowGet);
}

DeliveriesController:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "ID,DateOfDelivery,Driver")] Delivery delivery)
{
    if (ModelState.IsValid)
    {
        _rep.Save(delivery);
        return RedirectToAction("Index");
    }  

    return View(delivery);
}

查看:

@Html.JQueryUI().AutocompleteFor(m => m.Driver.Id, Url.Action("Drivers", "Employees"), "DriverId", null)

问题描述:
自动填充功能正常但在“编辑”视图中我发送POST请求时会收到所有数据,但ModelState.IsValid为false。 该错误显示FirstName和SecondName的字段为空,这是真的,因为我只发送了现有驱动程序的Id,而不是整个对象。
有办法解决吗?
也许某种方式可以将验证更改为不检查除Driver.Id存在之外的内部模型(驱动程序)字段。

0 个答案:

没有答案