DisplayFor 辅助方法呈现实体的 ID,但不会将其传递到 POST 表单集合
我很确定这是因为表单仅在提交表单时发布输入,不是吗?
因此,当我收到 POST 响应时,我编辑的名称被正确接收,但 ID 始终设置为 0。
有什么解决方法吗?
public ActionResult Edit(int id)
{
var productBrand = brandRepo.FindProductBrand(id);
ProductBrandModel model = Mapper.Map<ProductBrand, ProductBrandModel>(productBrand);
return View(model);
}
[HttpPost]
public ActionResult Edit(ProductBrandModel model)
{
if (ModelState.IsValid)
{
var productBrand = brandRepo.FindProductBrand(model.ProductBrandId);
productBrand.Name = model.Name;
brandRepo.SaveChanges();
return RedirectToAction("Index", "ProductBrands");
}
return View(model);
}
/* THIS IS THE VIEW*/
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>ProductBrandModel</legend>
<div class="editor-label">
@Html.LabelFor(model => model.ProductBrandId)
</div>
<div class="editor-field">
@Html.DisplayFor(model => model.ProductBrandId)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
</div>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
我不想让用户编辑实体的 ID,而只能编辑名称。
谢谢。
I'm pretty sure this is because the form only POSTS inputs when submitting a form, no?
So when I recieve a POST response, the name I edited is correctly received but the ID is always set to 0.
Any workarounds?
public ActionResult Edit(int id)
{
var productBrand = brandRepo.FindProductBrand(id);
ProductBrandModel model = Mapper.Map<ProductBrand, ProductBrandModel>(productBrand);
return View(model);
}
[HttpPost]
public ActionResult Edit(ProductBrandModel model)
{
if (ModelState.IsValid)
{
var productBrand = brandRepo.FindProductBrand(model.ProductBrandId);
productBrand.Name = model.Name;
brandRepo.SaveChanges();
return RedirectToAction("Index", "ProductBrands");
}
return View(model);
}
/* THIS IS THE VIEW*/
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>ProductBrandModel</legend>
<div class="editor-label">
@Html.LabelFor(model => model.ProductBrandId)
</div>
<div class="editor-field">
@Html.DisplayFor(model => model.ProductBrandId)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
</div>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
I don't want to let the users edit the ID of the entity, only the name.
Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
怎么样?
添加
@Html.HiddenFor(model => model.ProductBrandId)
如果我理解你的问题,我认为这会达到你想要的效果。
What about adding
@Html.HiddenFor(model => model.ProductBrandId)
I think that will do what you want, if I understand your question.