0

I'm fairly new to asp.net mvc3 and I am having a hard time figuring this out. I have an actionlink which i want to include a parameter and pass to my Index Method

@Html.ActionLink("Click here", "Index", "Customer", new { customerid = item.custId}, new {       @class = "partiallink" })

How do i receive it from the controller? considering that there is no method parameter in my Index Action method and also how do I output the parameter in the view?

I guess what I'm trying to say is pass it to some controller method and still returns the Index page with the paramters

shinra tensei
  • 693
  • 5
  • 20
  • 39

3 Answers3

1

All parameters that you pass to action link become a querystring parameter i.e.

@Html.ActionLink("Click here", "Index", "Customer", new { customerid = 111, someOtherParameter = 222, anotherParameter = 333}

transfer to link /Customer/Index?customerid=111&someOtherParameter=222&anotherParameter=333. You can get it in controller through Request.QueryStringproperty or map it through model binder if signature of Index action is:

ActionResult Index(int? customerid, int? someOtherParameter, string anotherParameter)
{
    .....
}
Kirill Bestemyanov
  • 11,946
  • 2
  • 24
  • 38
  • I don't know why the parameters I pass don't become part of the query string. Why is that? Does that mean it doesn't work for the current version of .net? – William May 28 '22 at 23:52
0

Are you saying, on your Customer controller, you want to be able to pass either no value, or a customerid to your Index action, which returns the Index page?

Assuming you haven't changed the default route, you can alter your controller action to accept a nullable int, and then get your model based on whether the customerid is null:

    public ActionResult Index(int? customerid)
    {
        YourModelType model;
        if (customerid == null)
        {
            model = /* however you get your model when you don't have an id */
        }
        else
        {
            model = /* however you get your model when you have an id */;
        }

        return View("Index", model);
    }

You'll also need to update your routing engine to accept the optional customerid parameter:

        routes.MapRoute(
            "Customer", // Route name
            "Customer/{action}/{customerid}", // URL with parameters
            new { controller = "Customer", action = "Index", customerid = UrlParameter.Optional } // Parameter defaults
        );
Mark Oreta
  • 10,346
  • 1
  • 33
  • 36
0

You can use similar to below example

@Html.ActionLink("Click here", "Index", "Customer", new { ID= 111,UID =222}, null)

and in controller

[HttpGet,Route("Index/{ID}/{UID}")]
        public ActionResult EventView(int ID,int UID)
        {
        }

Please refer below link as well ,it is useful

Query string not working while using attribute routing

Community
  • 1
  • 1
StackOrder
  • 270
  • 4
  • 14