有什么帮助来理解为什么我的字段没有在 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);
}
}
然后,当我访问/restaurant/index 时,我显然可以看到所有餐厅的列表,因为在 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>
}
我正在单击保存按钮,但是当我返回到索引时,我为名称输入的值没有记录。我在这里错过了什么?很明显,我错过了一些东西。如何进行更新?
以更直接的方式执行此操作是否更值得推荐,也许不使用帮助程序而只是将更新方法与保存按钮相关联?(只是说说而已(。
我忘了添加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
操作的权限。 创建一个带有HttpPostAttribute
的新ActionResult
,以及一个与模型匹配的参数,如下所示:
[HttpPost]
public ActionResult Edit(Restaurant restaurant)
{
//Save restaurant here
return RedirectToAction("Index");
}
ModelBinder
将选取此内容,并从提交的表单中为您填充restaurant
。