2010-11-20 7 views
17

ASP.NET MVC 3でIEnumerable <T>を編集するにはどうすればよいですか?

次の型を指定する

public class SomeValue 
{ 
    public int Id { get; set; } 
    public int Value { get; set; } 
} 

public class SomeModel 
{ 
    public string SomeProp1 { get; set; } 
    public string SomeProp2 { get; set; } 
    public IEnumerable<SomeValue> MyData { get; set; } 
} 

SomeProp1SomeProp2の通常のテキストフィールドを含むSomeModel型の編集フォームを作成し、次にSomeModel.MyDataコレクションの各SomeValueのテキストフィールドを含むテーブルを作成します。

これはどのように行われますか?値はどのようにしてモデルに戻されますか?

私は現在、各値のテキストフィールドを表示するフォームを持っていますが、それらはすべて同じ名前と同じIDを持っています。これは明らかに有効なHTMLではなく、MVCが値を戻すのを妨げます。

答えて

14

あなたはエディタテンプレートを使用します。このようにして、フレームワークは、入力フィールドの名前を正しく指定することから、ポストアクションで値を適切にバインドすることに至るまで、すべてを処理します。

コントローラー:

public class HomeController : Controller 
{ 
    public ActionResult Index() 
    { 
     // In the GET action populate your model somehow 
     // and render the form so that the user can edit it 
     var model = new SomeModel 
     { 
      SomeProp1 = "prop1", 
      SomeProp2 = "prop1", 
      MyData = new[] 
      { 
       new SomeValue { Id = 1, Value = 123 }, 
       new SomeValue { Id = 2, Value = 456 }, 
      } 
     }; 
     return View(model); 
    } 

    [HttpPost] 
    public ActionResult Index(SomeModel model) 
    { 
     // Here the model will be properly bound 
     // with the values that the user modified 
     // in the form so you could perform some action 
     return View(model); 
    } 
} 

ビュー(~/Views/Home/Index.aspx):

<% using (Html.BeginForm()) { %> 

    Prop1: <%= Html.TextBoxFor(x => x.SomeProp1) %><br/> 
    Prop2: <%= Html.TextBoxFor(x => x.SomeProp2) %><br/> 
    <%= Html.EditorFor(x => x.MyData) %><br/> 
    <input type="submit" value="OK" /> 
<% } %> 

、自動的にMyDataコレクションの各要素に対して呼び出されます最終的にはエディタテンプレート(~/Views/Home/EditorTemplates/SomeValue.ascx):

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<MyApp.Models.SomeValue>" %> 
<div> 
    <%= Html.TextBoxFor(x => x.Id) %> 
    <%= Html.TextBoxFor(x => x.Value) %> 
</div> 
+0

あなたは答えが既に良いので、私は今それを投稿しないだろうと思う:)私はあなたが簡単にリストをバインドできるか分からなかった。おかげで – Buildstarted

+2

MVC3のためにそれは剃刀を使用する方が良いですか? – arame3333

1

IListはIEnumerableを実装しています

public class SomeModel { 
    public string SomeProp1 { get; set; } 
    public string SomeProp2 { get; set; } 
    public IList<SomeValue> MyData { get; set; } 
} 

あなたはあなたの特定のモデル用のバインダーを作成するためにIModelBinderインタフェースを使用することができます。それを行うにはいくつかの方法があります。モデルのEditorFor cshtmlを作成してSomeValueリストをループし、適切なIDとそれ以外のものを出力できます。次に、ModelBinderの実装では、あなたのIDを読み取って適切にバインドします。私はしばらくの間、作業サンプルを投稿することができます。

+0

フォームが送信されると、ViewEngin eデータをコレクション内の正しい要素にバインドして処理しますか? –

+0

あなたは本当に奇妙なことを知っています...私は**誓いを持つことができました**この質問は別のものを求めました...私は同時に2つの質問を読んでいて、間違った答えをしていたと思います...私の答えを変更してください – Buildstarted

関連する問題