我每次都面臨ModelState.IsValid false。我調試了整個動作。當我展開ModelState錯誤部分時,我發現System.Web.Mvc.Model錯誤。在我的模型中,Status屬性通過Data Annotation聲明爲Required。所以基本上這個錯誤表明我的狀態在模型中是必需的。這就是爲什麼它給出驗證錯誤。ASP.NET MVC 5 ModelState.IsValid始終在MVC中返回false
這是我的模型
public class CompanyResource
{
[Key]
public int Id { get; set; }
[Required]
[StringLength(100)]
public string Name { get; set; }
[StringLength(100)]
public string Position { get; set; }
[Display(Name="Date of Joining")]
public DateTime? DOJ { get; set; }
[StringLength(50)]
public string Phone { get; set; }
[StringLength(100)]
public string Address { get; set; }
[StringLength(1)]
[Required]
public string Status { get; set; }
public virtual ICollection<ProjectResource> ProjectResources { get; set; }
public virtual ICollection<ProjectSiteResource> ProjectSiteResources { get; set; }
}
}
這是我行動
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,Name,Position,DOJ,Phone,Address,Status")] CompanyResource companyResource)
{
var isAjaxRequest = Request.IsAjaxRequest();
ModelState["Status"].Errors.Clear();
if (ModelState.IsValid)
{
db.CompanyResource.Add(companyResource);
db.SaveChanges();
if (isAjaxRequest)
{
var staff = new SelectList(db.CompanyResource.ToList(), "Id", "Name");
return Json(new { Flag = true, CompanyResources = staff }, JsonRequestBehavior.AllowGet);
}
Success(string.Format("Successfully save data !"), true);
return RedirectToAction("Index");
}
if (!isAjaxRequest) return View(companyResource);
return Json(null, JsonRequestBehavior.AllowGet);
}
這是我在同一個控制器的另一種方法
public JsonResult GetStaff()
{
try
{
var staff = new SelectList(db.CompanyResource.ToList(), "Id", "Name");
return Json(new { Flag = true, CompanyResources = staff }, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
return Json(new { Flag = false, Msg = ex.Message }, JsonRequestBehavior.AllowGet);
}
}
這是我的查看
<div class="form-group">
@Html.Label("Status", htmlAttributes: new { @class = "control-label col-md-2", @required = "required" })
<div class="col-md-10">
<select class="form-control" id="Status">
<option value="A">Active</option>
<option value="I">Inactive</option>
</select>
</div>
</div>
你檢查所有數據的註釋......所有的人都需要有一個顯示名稱模型.. –
我檢查。該屬性設置爲[必需]。 – Nabid
您是不是從UI填充狀態值? –