开发者

Action method with two arguments

开发者 https://www.devze.com 2023-03-28 16:36 出处:网络
I need to have two arguments in action method: one for id of article and second with model of comment.

I need to have two arguments in action method: one for id of article and second with model of comment.

I wrote form in article which have action Articles/{id}/AddComment.

        routes.MapRoute(
            "Article_action", // Route name
            "Articles/{id}/{action}", // URL with parameters
            new { controller 开发者_StackOverflow中文版= "Articles" } // Parameter defaults
        );

My form:

<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>

Here is my ArticleViewModelResponse:

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

My action method:

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

Here is a problem... comment argument always has null value but id is correct. And if I change type ArticleViewModelResponse to FormCollection then comment has every variables.

Where is the problem? Why FormCollection has evethings and ArticleViewModelResponse doesnt?

P.S. Of course this is only example demonstrates my problem and it isnt all my code. So ignore every misspeling.


It looks the names of your input elements are wrong, you need to prefix them with the parameters name, try this:

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


Try creating a view model class like below.

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) 
  {   //...   } 

Now the Id will be part of view model class that will be automatically send to controller.

Thanks, -Naren


Add routing rule in global.asax.cs file.

0

精彩评论

暂无评论...
验证码 换一张
取 消