2011-01-03 19 views
19

ASP.NET MVCのアクションに複数のパラメータを送信したいと思います。私も、このように見えるようにURLが欲しい:ASP.NET MVCのアクションに複数のパラメータを送信

http://example.com/products/item/2 

の代わり:

http://example.com/products/item.aspx?id=2 

私も、送信者のために同じことをしたいと思いますが、ここでは現在のURLです

http://example.com/products/item.aspx?id=2&sender=1 

ASP.NET MVCでC#を使用するにはどうすればよいですか?

答えて

26

クエリ文字列を渡しても問題ない場合は、非常に簡単です。単純に一致する名前を持つ追加のパラメータを取るためにアクションメソッドを変更:

// Products/Item.aspx?id=2 or Products/Item/2 
public ActionResult Item(int id) { } 

になるだろう:

// Products/Item.aspx?id=2&sender=1 or Products/Item/2?sender=1 
public ActionResult Item(int id, int sender) { } 

ASP.NET MVCはあなたのためにすべてをアップ配線の作業を行います。

あなたはクリーン探してURLをしたい場合、あなたは、単にGlobal.asax.csに新しいルートを追加する必要があります。

// will allow for Products/Item/2/1 
routes.MapRoute(
     "ItemDetailsWithSender", 
     "Products/Item/{id}/{sender}", 
     new { controller = "Products", action = "Item" } 
); 
+0

URLの形式は何ですか? – Reza

+0

あなたのglobal.asaxでルートの適切な定義を設定することを忘れないでください。 –

+0

@Reza - コードにURLをコメントとして追加しました。よりクリーンなURLが必要な場合は、global.asax.csへのカスタムルートを追加する必要があります。 –

4

あなたは、たとえば任意の経路ルールを使用することができます。

{controller}/{action}/{param1}/{param2} 

また、あなたが:baseUrl?param1=1&param2=2

のようなのparamsを取得し、this linkを確認する使用することができ、私はそれはあなたを助けることを願っています。

12

かなりのURLが必要な場合は、global.asax.csに以下を追加してください。

routes.MapRoute("ProductIDs", 
    "Products/item/{id}", 
    new { controller = Products, action = showItem, id="" } 
    new { id = @"\d+" } 
); 

routes.MapRoute("ProductIDWithSender", 
    "Products/item/{sender}/{id}/", 
    new { controller = Products, action = showItem, id="" sender="" } 
    new { id = @"\d+", [email protected]"[0-9]" } //constraint 
); 

そして使用するために必要なアクション:

public ActionResult showItem(int id) 
{ 
    //view stuff here. 
} 

public ActionResult showItem(int id, int sender) 
{ 
    //view stuff here 
} 
関連する問題