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

回答

0

你應該渲染視圖中模型的ID,並使用另一重載Html.BeginForm如下:

@using (Html.BeginForm("Edit", "Controller", FormMethod.Post, new{attr1 = value1, attr2 = value2})) 
{ 
    @Html.HiddenFor(x => x.Id) 
    ... 
} 

你總是讓後到EditAction。在你的控制器中,你只需要一個POST動作進行編輯,兩個獲得動作一個創建和其他編輯。

public ActionResult Create() 
{ 
    return View("Edit"); //return the edit view 
} 

public ActionResult Edit(int id) 
{ 
    var entity = manager.FetchById(id); 
    if (entity == null) 
     return HttpNotFound(); 

    //convert your entity to model (optional, but recommended) 
    var model = Mapper.Map<ViewModel>(entity); 

    //return your edit view with your model 
    return View(model); 
} 

[HttpPost] 
public ActionResult Edit(ViewModel model) 
{ 
    if (ModelState.IsValid) 
    { 
     //work with your model 

     return RedirectToAction("Index", "Controller"); 
    } 

    //at this point there is an error, so your must return your view 
    return View(model); 
} 

希望這有助於!

相關問題