10

Using MVC 3 Razor, how can I specify a variable within a call to @Url.Content().

Example:

@{
var myVar = Request.QueryString["foo"];
}

<a href="@Url.Content("~/bar?@myvar")">click here</a>

2 Answers 2

21

You're already in the c# context at that point, so you can use the variable just like you would in a code file. Try this:

<a href="@Url.Content("~/bar?" + myvar)">click here</a>
Sign up to request clarification or add additional context in comments.

2 Comments

With all the magic we get in Mvc/Razor, I was hoping that there would be a syntax that doesn't involve a concatenator. Thanks, Kyle.
@Jed - use string.Format. Or better yet, create a UrlHelper extension that accepts the variable in the method and bubbles up to Url.Content. But looking at your example, perhaps Html.ActionLink is a better option, then you can pass in the variable as route params.
0

Building up on RPM1984 comment, you could also do:

<a href="@Url.Content(string.Format("~/bar?{0}",myvar))">click here</a>

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.