Pass parameter to controller from @Html.ActionLink MVC 4

You are using a wrong overload of the Html.ActionLink helper. What you think is routeValues is actually htmlAttributes! Just look at the generated HTML, you will see that this anchor’s href property doesn’t look as you expect it to look.

Here’s what you are using:

@Html.ActionLink(
    "Reply",                                                  // linkText
    "BlogReplyCommentAdd",                                    // actionName
    "Blog",                                                   // routeValues
    new {                                                     // htmlAttributes
        blogPostId = blogPostId, 
        replyblogPostmodel = Model, 
        captchaValid = Model.AddNewComment.DisplayCaptcha 
    }
)

and here’s what you should use:

@Html.ActionLink(
    "Reply",                                                  // linkText
    "BlogReplyCommentAdd",                                    // actionName
    "Blog",                                                   // controllerName
    new {                                                     // routeValues
        blogPostId = blogPostId, 
        replyblogPostmodel = Model, 
        captchaValid = Model.AddNewComment.DisplayCaptcha 
    },
    null                                                      // htmlAttributes
)

Also there’s another very serious issue with your code. The following routeValue:

replyblogPostmodel = Model

You cannot possibly pass complex objects like this in an ActionLink. So get rid of it and also remove the BlogPostModel parameter from your controller action. You should use the blogPostId parameter to retrieve the model from wherever this model is persisted, or if you prefer from wherever you retrieved the model in the GET action:

public ActionResult BlogReplyCommentAdd(int blogPostId, bool captchaValid)
{
    BlogPostModel model = repository.Get(blogPostId);
    ...
}

As far as your initial problem is concerned with the wrong overload I would recommend you writing your helpers using named parameters:

@Html.ActionLink(
    linkText: "Reply",
    actionName: "BlogReplyCommentAdd",
    controllerName: "Blog",
    routeValues: new {
        blogPostId = blogPostId, 
        captchaValid = Model.AddNewComment.DisplayCaptcha
    },
    htmlAttributes: null
)

Now not only that your code is more readable but you will never have confusion between the gazillions of overloads that Microsoft made for those helpers.

Leave a Comment