admin管理员组

文章数量:1356702

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

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

Share Improve this question asked Sep 8, 2011 at 18:08 Anthony QueenAnthony Queen 2,3683 gold badges18 silver badges21 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 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.

本文标签: aspnet mvc 3MVC3Dynamic URL redirect in JavascriptStack Overflow