我每次都面对一个ModelState.IsValid false。我调试了整个动作。当我展开ModelState错误部分时,我发现System.Web.Mvc.Model错误。在我的模型中,Status属性通过Data Annotation声明为Required。所以基本上错误表明我的状态在模型中是必需的。这就是它给出验证错误的原因。
这是我的模特
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>
答案 0 :(得分:3)
在您的问题的评论中,您表明这是您的HTML和型号:
<select class="form-control" id="Status">
<option value="A">Active</option>
<option value="I">Inactive</option>
</select>
[StringLength(1)] [Required] public string Status { get; set; }
您需要为MVC绑定设置select标记的name
属性才能生效。所以添加如下名称:
<select class="form-control" id="Status" name="Status">
<option value="A">Active</option>
<option value="I">Inactive</option>
</select>