2016-09-15 49 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); 
} 

希望这有助于!

相关问题