LoginSignup
23
18

More than 5 years have passed since last update.

ASP.NET MVC ViewからControllerへ値をModelに詰めて渡す方法

Posted at

ASP.NET MVC ViewからControllerへ値を渡す方法の続きです。
環境は以下の通りです。
・Visual Studio 2015
・ASP.NET MVC5

Viewに複数のinputやselectなど入力項目がある場合に、
それらをModelに詰めて、ViewからControllerにデータを渡す方法です。

viewからcontorllerへ値を渡す方法

Modelを使わない方法

以下の様なViewがあるとします。

  <input type="text" name="data1" />
  <input type="text" name="data2" />
  <input type="text" name="data3" />

※上記の記載はformタグで囲まれています。

この値をControllerに渡したいとすると・・・もちろんcontroller側のアクションの引数を以下の様してもOKです。

public ActionResult Action1(string data1, string data2, string data3)
{
    中身・・・
}

Viewのinputタグのnameの値と、Controllerのアクションの引数名を一致させればOKです。
これで自動的に紐づけをしてくれます。

Modelを使う方法

ただ、渡す項目が多くなった時、上記の「引数に全項目を書く」方法をとるのは大変だし可読性もよくありません。
そこで、項目をModelに詰めて渡したいと思います。
以下の様に、Viewの入力項目のnameとおなじ名前のフィールドを
持つModelを作ります。

  public class SampleModel
  {
    public string data1 { get; set; }
    public string data2 { get; set; }
    public string data3 { get; set; }
  }

Controllerのアクションの引数を、上記のModelにします。

public ActionResult Action1(SampleModel model)
{
    中身・・・
}

これで、ViewからControllerへ、Modelを値を渡すことができます。

23
18
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
23
18