2

I am using C#, MVC3, and Razor.

I have a javascript function (in the view) that gets called when a particular menu item is clicked. In this function, I need to build a new URL with parameters (based on other selections on the screen) and redirect to it. It want it to do something like this:

ValueA and ValueB are variables in the javascript section and are populated with values.

function doSomething(ID) {
    location.href =  "../Area/Controller/Action?ID=" + ID + "&ValueA=" + ValueA + "&ValueB=" + ValueB;
  }

However, due to the nature of MVC I need to make sure the URL is always right, regardless of how the user got to the page. I've tried to use @Url.Content("") (see next code block) but the issue I run into is:

  • The name 'ID' does not exist in the current context
  • The name 'ValueA' does not exist in the current context
  • The name 'ValueB' does not exist in the current context

Here is an example of what I would like to do but get the above mentioned errors on:

function doSomething(ID) {
    location.href = @Url.Content("~/Area/Controller/Action?ID=" + ID + "&ValueA=" + ValueA + "&ValueB=" + ValueB);
  }

How can I make this work? Is there a better way?

Thanks, Tony

1 Answer 1

6

You should concatenate the the static part to the dynamic part:

location = "@Url.Content("~/Area/Controller/Action")?ID=" + ID + "&ValueA=" + ValueA + "&ValueB=" + ValueB;

The outer "@...?ID=" is a Javascript string literal.
@Url.Content("...") is server-side code that emits raw text into the Javascript literal.

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

3 Comments

Works great! This makes a lot of sense. I'm wishing I had thought of it.
BTW, you should call @Url.Action instead of Content.
Thanks. I've modified the code to use @Url.Action since it is in the same controller as the current view. Works great.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.