我尝试过使用:
@Html.HiddenFor(m => m.CategoryId)
和
<input type="hidden" name="@Model.CategoryId"
id="CategoryId" value="@Model.CategoryId" />
但似乎没有人回发CategoryId并将其绑定,我收到的所有内容都是默认值0,这使我无法编辑我的模型
在post方法中使用FormCollection,我确实得到了值,但是我想要默认的模型绑定器来实现它。
这是我的控制器:
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Category category = db.Categories.Find(id);
if (category == null)
{
return HttpNotFound();
}
return View(category);
}
[HttpPost]
public ActionResult Edit([Bind(Include = "CategoryId, Name")] Category category)
{
if (ModelState.IsValid)
{
db.Entry(category).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(category);
}
这是我的观点:
@model Category
@using (Html.BeginForm())
{
<div>
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<input type="hidden" name="CategoryId" value=@Model.CategoryId id="CategoryId"/>
<div>
@Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
<div>
@Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div>
<input type="submit" value="Save" class="btn" />
</div>
</div>
</div>
}
修改 这是我的模特:
[MetadataType(typeof(CategoryValidation))]
public class Category
{
public Category()
{
Features = new List<Feature>();
Products = new List<Product>();
}
[HiddenInput(DisplayValue = false)]
public int CategoryId { get; set; }
public string Name { get; set; }
public virtual ICollection<Feature> Features { get; set; }
public virtual ICollection<Product> Products { get; set; }
}
第二次编辑 我可以简单地在HttpPost Action中使用FormCollection或者使用&#34;(int?id)&#34;在修改数据库状态之前手动绑定已发布模型的ID,但为什么ModelBinder在发布模型时不会这样做呢?
答案 0 :(得分:0)
问题来自我的模型从
中检索数据注释的另一个类[Bind(Exclude = "CategoryId")]
public class CategoryValidation
{
[Display(Name = "Category's Name")]
public string Name { get; set; }
}
[MetadataType(typeof(CategoryValidation))]
public class Category
{
public Category()
{
Features = new List<Feature>();
Products = new List<Product>();
}
[HiddenInput(DisplayValue = false)]
public int CategoryId { get; set; }
public string Name { get; set; }
public virtual ICollection<Feature> Features { get; set; }
public virtual ICollection<Product> Products { get; set; }
}
删除属性[Bind(Exclude =“CategoryId”)]允许ModelBinder正确绑定Id
这适用于使用Razor语法HiddenFor Html Helper方法和输入类型隐藏标记