带有两个参数的Action方法

时间:2011-08-15 08:48:29

标签: c# asp.net-mvc model-view-controller asp.net-mvc-3

我需要在action方法中有两个参数:一个用于文章的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) {
//...
}

这是一个问题...注释参数始终具有空值但id是正确的。如果我将类型ArticleViewModelResponse更改为FormCollection,则注释包含每个变量。

问题出在哪里?为什么FormCollection有evethings而ArticleViewModelResponse没有?

P.S。当然这只是示例,演示了我的问题,而且不是我的所有代码。所以忽略每一个拼写错误。

3 个答案:

答案 0 :(得分:1)

看起来输入元素的名称是错误的,你需要在它们前面加上参数名称,试试这个:

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

答案 1 :(得分: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

答案 2 :(得分:0)

在global.asax.cs文件中添加路由规则。