任何幫助理解爲什麼我的領域沒有在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。以更直接的方式進行此操作會更值得推薦嗎?也許不需要使用幫助器,只需將更新方法與保存按鈕相關聯即可? (只是說說)。
是否在編輯頁面上點擊「保存」實際上做了什麼?我沒有看到任何代碼來實際更新任何東西。 – Becuzz
@Becuzz不需要。 OP在「BeginForm」中封裝了邏輯,可能需要傳入參數和/或「Id」來定位控制器/方法。我通常不使用BeginForm ...而是猜測。 - https://msdn.microsoft.com/en-us/library/system.web.mvc.html.formextensions.beginform(v=vs.118).aspx –
您沒有'ActionMethod'來接收POST數據。它應該看起來像'[HttpPost] public ActionResult Edit(RestaurantModel restaurant)' –