0
当您在VS上创建新的脚手架项目时,它会创建几乎相同的创建和编辑操作的视图,但编辑视图的主视图为@Html.HiddenFor
键。使用相同的部分将表单添加到创建和编辑动作
编辑观点的例子:
@model MyApp.Models.Destaque
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
@Html.HiddenFor(m => m.IdDestaque)
<div class="form-group">
@Html.LabelFor(model => model.Mensagem, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Mensagem, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Mensagem, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.CaminhoImagem, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.CaminhoImagem, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.CaminhoImagem, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.UrlLink, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.UrlLink, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.UrlLink, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Salvar" class="btn btn-primary" />
</div>
</div>
</div>
}
如果我把从BeginForm
(包括@using (...
)的所有内容,并保持在一个_form部分的@Html.HiddenFor(m => m.IdDestaque)
,它不允许我去创建新行。
如果我从_Form部分删除@Html.HiddenFor
,则编辑操作不起作用(模型状态无效)。
那么做到这一点并保持DRY原则的正确方法是什么?在我的“编辑”操作中从ModelState验证中删除PK似乎是一种“不好”的解决方法。