0

I have a controller method that looks like

public ViewResult Index(string id, string participant="", string flagged = "")

id is a route value in my global.asax for this controller. I want to pass in the other values as regular arguments so the link would look like

.../controller/Index/id?participant=yes&flagged=no

Is there a way to generate a link like this using Razor script in MVC 3?

2 Answers 2

7

You could pass all parameters in the routeValues argument of the ActionLink method:

@Html.ActionLink(
    "go to index",                  // linkText
    "index",                        // actionName
    new {                           // routeValues
        id = "123", 
        participant = "yes", 
        flagged = "no" 
    }
)

Assuming default routing setup this will generate:

<a href="/Home/index/123?participant=yes&amp;flagged=yes">go to index</a>

UPDATE:

To further elaborate on the comment you have posted, if the ActionLink generated an url with Length=6 for example this means that you have used the wrong overload. For example this is wrong:

@Html.ActionLink(
    "go to index",             // linkText
    "index",                   // actionName
    "home",                    // routeValues
    new {                      // htmlAttributes
        id = "123", 
        participant = "yes", 
        flagged = "no" 
    }
)

It is obvious why this is wrong from the comments I've put along each parameter name. So make sure you are carefully reading the Intellisense (if you are lucky enough to have Intellisense working in Razor :-)) to pick the correct overload of the helper methods.

The correct overload in the case you want to specify a controller name is the following:

@Html.ActionLink(
    "go to index",             // linkText
    "index",                   // actionName
    "home",                    // controllerName
    new {                      // routeValues
        id = "123", 
        participant = "yes", 
        flagged = "no" 
    },
    null                       // htmlAttributes
)

Notice the null that is passed as last argument. That's what corresponds to the htmlAttributes parameter.

Sign up to request clarification or add additional context in comments.

2 Comments

I could have sworn I tried this already and for some reason it was giving me a parameter of Length=6 but it worked.
@DarinDimitrov has answered my simple question once again....and gave details to his answer. Thanks!
3

You can use an ActionLink for this:

@Html.ActionLink("Title",
                 "ActionName", 
                  new {id = 1, participant = "yes", flagged = "no"})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.