2011-08-15 27 views
0

我需要在動作方法中有兩個參數:一個用於文章的id,另一個用於評論的模型。帶兩個參數的動作方法

我在文章具有行動文章/ {ID}/AddComment寫道形式。

 routes.MapRoute(
      "Article_action", // Route name 
      "Articles/{id}/{action}", // URL with parameters 
      new { controller = "Articles" } // Parameter defaults 
     ); 

我的形式:

<form action="@Url.RouteUrl(new { controller = "Articles", id = article.article_id, action = "AddComment" })" method="post"> 
<input type="hidden" name="article_id" value="@article.article_id" /> 
<textarea name="comment" rows="6" cols="30"></textarea> 
<input type="submit" /> 
</form> 

這裏是我的ArticleViewModelResponse:

public class ArticleViewModelResponse { 
    public int article_id{set;get;} 
    public string comment{set;get;} 
} 

我的操作方法:

[HttpPost] 
public ActionResult DodajKomentarz(int id, ArticleViewModelResponse comment) { 
//... 
} 

這裏有一個問題... comment參數總是有空值,但id是正確的。如果我將類型ArticleViewModelResponse更改爲FormCollection,則評論具有每個變量。

問題在哪裏?爲什麼FormCollection有evethings和ArticleViewModelResponse沒有?

P.S.當然,這只是一個例子,證明了我的問題,並不是我所有的代碼。所以忽略每一個拼寫錯誤。

+1

你添加一個路線呢? –

回答

1

看起來你輸入元素的名稱是錯誤的,你需要的參數名稱的前綴他們,試試這個:

<input type="hidden" name="comment.article_id" value="@article.article_id" /> 
<textarea name="comment.comment" rows="6" cols="30"></textarea> 
+0

謝謝。就是這個! :) – nosbor

0

嘗試創建一個視圖模型類,如下所示。

public class ArticleViewModelResponse {  
     public int article_id{set;get;}  
     public string comment{set;get;} 
     public int Id {get; set;} 
    } 

[HttpPost] 
    public ActionResult DodajKomentarz(ArticleViewModelResponse comment) 
    { //... } 

現在Id將成爲視圖模型類的一部分,該視圖模型類將自動發送給控制器。

感謝, -Naren

+0

仍然是同樣的問題。也許我應該做點別的? – nosbor

0

在添加文件的global.asax.cs路由規則。

+0

當然有一個規則。如果我不添加規則,那麼我的操作方法就不必啓動了。 – nosbor