我有一个表单将id字段绑定为隐藏值。但在控制器中,id(键,自动标识增量)字段始终为0.以下是我的代码:
Model.cs
public partial class A
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int id { get; set; }
[StringLength(255)]
[Display(Name = "Institution Name")]
[Required]
public string InstitutionName { get; set; }
[Display(Name = "Public")]
[DefaultValue(false)]
public bool Category1 { get; set; }
[Display(Name = "Private")]
[DefaultValue(false)]
[Display(Name = "Online")]
[DefaultValue(false)]
public bool Category3 { get; set; }
[
[Display(Name = "Active?")]
[DefaultValue(false)]
public bool active { get; set; }
public A()
{
Category1 = false;
Category2 = false;
Category3 = false;
active = true;
}
}
控制器:
...
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "id,InstitutionName,Category1,Category2,Category3,active")] A A)
{
if (ModelState.IsValid)
{
db.A.Add(A);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(A);
}
}
...
查看 - Create.cshtml:
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>TransferSearch_revised</h4>
<hr />
@Html.HiddenFor(model=> model.id)
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.InstitutionName, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.InstitutionName, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.InstitutionName, "", new { @class = "text-danger" })
</div>
</div>
...
id值为0或为空。我的代码出了什么问题?感谢。