[razor] Pass parameter to controller from @Html.ActionLink MVC 4

In this line:

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

I get the following runtime error on blogPostId:

The parameters dictionary contains a null entry for parameter 'blogPostId' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult BlogReplyCommentAdd(Int32, Nop.Web.Models.Blogs.BlogPostModel, Boolean)' in 'Nop.Web.Controllers.BlogController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter. Parameter name: parameters

I have already assign a value for this on top such as

    @{         
        var blogPostId = Model.Id;          
     }

My Controller:

 public ActionResult BlogReplyCommentAdd(int blogPostId, BlogPostModel model, bool captchaValid)
    {}

Am I doing something wrong? Please give me an example.

This question is related to razor asp.net-mvc-4

The answer is


The problem must be with the value Model.Id which is null. You can confirm by assigning a value, e.g

@{         
     var blogPostId = 1;          
 }

If the error disappers, then u need to make sure that your model Id has a value before passing it to the view


You can pass values by using the below .

@Html.ActionLink("About", "About", "Home",new { name = ViewBag.Name }, htmlAttributes:null )

Controller:

public ActionResult About(string name)
        {
            ViewBag.Message = "Your application description page.";
            ViewBag.NameTransfer = name;
            return View();
        }

And the URL looks like

http://localhost:50297/Home/About?name=My%20Name%20is%20Vijay

I have to pass two parameters like:

/Controller/Action/Param1Value/Param2Value

This way:

@Html.ActionLink(
    linkText,
    actionName,
    controllerName,
    routeValues: new {
        Param1Name= Param1Value, 
        Param2Name = Param2Value 
    },
    htmlAttributes: null
)

will generate this url

/Controller/Action/Param1Value?Param2Name=Param2Value

I used a workaround method by merging parameter two in parameter one and I get what I wanted:

@Html.ActionLink(
    linkText,
    actionName,
    controllerName,
    routeValues: new {
        Param1Name= "Param1Value / Param2Value" ,      
    },
    htmlAttributes: null
)

And I get :

/Controller/Action/Param1Value/Param2Value