2011-09-26 7 views

答えて

86

まず、大文字と小文字を区別します。

@model(小文字の「M」)ビューの上部にあるモデルの型を宣言するためにカミソリビューの予約キーワード、例えば次のとおりです。

以降のファイルで@model MyNamespace.Models.MyModel

、あなたが参照できますが、属性は@Model.Attribute(大文字の「M」)で指定します。

@modelがモデルを宣言します。 Modelはモデルのインスタンス化を参照します。

第2に、モデルに値を割り当ててページの後半で使用できますが、フォームがフォームフィールドの値でない限り、ページがコントローラアクションに送信されたときに永続的になりません。モデルバインディングプロセス中にバックモデルに値を得るために、あなたは例えば、フォームフィールドに値を代入する必要があります:あなたが作成する必要があり、あなたのコントローラのアクションで

オプション1

あなたのページの最初のビューのモデル、それ以外の場合Model.Attributeを設定しようとすると、Modelオブジェクトはnullになります。

コントローラー:

// This accepts [HttpGet] by default, so it will be used to render the first call to the page 
public ActionResult SomeAction() 
{ 
    MyModel model = new MyModel(); 
    // optional: if you want to set the property here instead of in your view, you can 
    // model.Attribute = "whatever"; 
    return View(model); 
} 

[HttpPost] // This action accepts data posted to the server 
public ActionResult SomeAction(MyModel model) 
{ 
    // model.Attribute will now be "whatever" 
    return View(model); 
} 

ビュー:

@{Model.Attribute = "whatever";} @* Only do this here if you did NOT do it in the controller *@ 
@Html.HiddenFor(m => m.Attribute); @* This will make it so that Attribute = "whatever" when the page submits to the controller *@ 

オプション2

あるいは、モデルが名前ベースであるため、あなたのコントローラでモデルを作成スキップすることができ、ちょうどフォームフィールドには、モデルプロパティと同じ名前を付けます。この場合、「属性」という名前の隠しフィールドを「任意」に設定すると、ページが送信されるときに、モデルバインディング処理中にモデルのAttributeプロパティにバインドされる値「何でも」が確実に確保されます。隠しフィールドである必要はなく、name="Attribute"のHTML入力フィールドのみであることに注意してください。

コントローラー:

public ActionResult SomeAction() 
{ 
    return View(); 
} 

[HttpPost] // This action accepts data posted to the server 
public ActionResult SomeAction(MyModel model) 
{ 
    // model.Attribute will now be "whatever" 
    return View(model); 
} 

ビュー:

@Html.Hidden("Attribute", "whatever");

+1

このいただきありがとうございます。素晴らしい答え。 – levteck

+1

この回答は名声の殿堂に入るはずです – petric

関連する問題