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似乎是一種「不好」的解決方法。