2017-08-01 5 views
1

私のフィールドがMvcで更新されない理由とこれを正しく修正する方法を理解する助けとなるでしょうか?EditorForのMvcでフィールドが更新されないのはなぜですか?

@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 }) 

    } 

:私は/レストラン/インデックスにアクセスするとき、私は明らかに私が持っているので、Index.cshtmlのレストランのリストを見ることができ、その後

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); 
     } 
} 

この

は私のコントローラであり、編集リンクをクリックすると、このビューが表示されます(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> 
      } 

私は私がインデックスに戻るときに名前に入力した値は記録されません。私はここで何が欠けていますか?私は何かが欠けていることはかなり明らかです。どのように更新を行うことができますか?

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レストラン)' –

答えて

0

私は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); 
     } 
0

あなたはHttpGetアクションのActionResultを持っているが、何もHttpPostアクションを受信しないように。それにHttpPostAttributeで新しいActionResultを作成し、このように、モデルに一致する引数:

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

    return RedirectToAction("Index"); 
} 

ModelBinderはこれを拾うと、提出されたフォームからあなたのためのrestaurantに移入されます。

関連する問題