为什么我的字段没有使用EditorFor在Mvc中更新?

问题描述:

任何帮助理解为什么我的领域没有在Mvc更新,以及如何正确解决这个问题?为什么我的字段没有使用EditorFor在Mvc中更新?

这是我的控制器:

public class RestaurantController : Controller 
{ 
     static List<RestaurantModel> rr = new List<RestaurantModel>() 
     { 
      new RestaurantModel() { Id = 1, Name = "Kebabs", Location = "TX" }, 
      new RestaurantModel() { Id = 2, Name = "Flying Donoughts", Location = "NY" } 
     }; 
     public ActionResult Index() 
     { 
      var model = from r in rr 
       orderby r.Name 
       select r; 
      return View(model); 
     } 
     public ActionResult Edit(int id) 
     { 
      var rev = rr.Single(r => r.Id == id); 
      return View(rev); 
     } 
} 

然后,当我访问/餐厅/指数,我明显可以看到所有的餐馆名单,因为在Index.cshtml我:

@model IEnumerable<DCForum.Models.RestaurantModel> 

    @foreach (var i in Model) 
    { 
     @Html.DisplayFor(myitem => i.Name) 
     @Html.DisplayFor(myitem => i.Location) 
     @Html.ActionLink("Edit", "Edit", new { id = i.Id }) 

    } 

当我点击编辑链接时,这个视图被触发(Edit.cshtml):

@model DCForum.Models.RestaurantModel 
      @using(Html.BeginForm()) { 
       @Html.ValidationSummary(true) 

       <fieldset> 
        @Html.HiddenFor(x => x.Id) 
        @Html.EditorFor(x => x.Name) 
        @Html.ValidationMessageFor(x => x.Name) 

        <input type="submit" value="Save" /> 
       </fieldset> 
      } 

我点击s ave按钮,但是当我返回到索引时,我为Name输入的值不会被记录。我在这里错过了什么?这很明显,我错过了一些东西。我怎样才能使更新发生?

PS。以更直接的方式进行此操作会更值得推荐吗?也许不需要使用帮助器,只需将更新方法与保存按钮相关联即可? (只是说说)。

+0

是否在编辑页面上点击“保存”实际上做了什么?我没有看到任何代码来实际更新任何东西。 – Becuzz

+1

@Becuzz不需要。 OP在“BeginForm”中封装了逻辑,可能需要传入参数和/或“Id”来定位控制器/方法。我通常不使用BeginForm ...而是猜测。 - https://msdn.microsoft.com/en-us/library/system.web.mvc.html.formextensions.beginform(v=vs.118).aspx –

+0

您没有'ActionMethod'来接收POST数据。它应该看起来像'[HttpPost] public ActionResult Edit(RestaurantModel restaurant)' –

我忘了添加HttpPost方法。非常感谢你指出这一点。

[HttpPost] 
     public ActionResult Edit(int id, FormCollection collection) 
     { 

      var review = rr.Single(r => r.Id == id); 
      if (TryUpdateModel(review)) 
      { 
       return RedirectToAction("Index"); 
      } 
      return View(review); 
     } 

你必须为HttpGet行动的ActionResult,但没有接收HttpPost行动。创建一个新的ActionResultHttpPostAttribute就可以了,该模型,这样相匹配的说法:

[HttpPost] 
public ActionResult Edit(Restaurant restaurant) 
{ 
    //Save restaurant here 

    return RedirectToAction("Index"); 
} 

ModelBinder会挑选这件事,并从已提交的表格填充restaurant你。