1

I would like to put a URL in an @Url.Content("").

I allow the user to choose their home page in my portal (as long as they display anything unnecessary on the home page) and I put this value in a column of my User table.

As long as this column is null I display a modal to select its home page. So once the connection returns "Success", I redirect to the correct page, but I am not able to pass a variable in @Url.Content(HERE) with the value in my column (Example: /Home/Index).

Here is my code:

IdentificationSucces = function(data) {
  if (@Session["SpAccueilDefaut"]) {
    var url = @Session["SpAccueilDefaut"].ToString();
    window.location.href = '@Url.Action("" + url +"")';
  } else {
    window.location.href = '@Url.Content("~/Intranet/Index")';
  }
};

My url variable is in error and this is the message:

The name'url' does not exist in the current context

1
  • If @Session["SpAccueilDefaut"] contains a url then you want just window.location.href = "@Session["SpAccueilDefaut"].ToString()" (without the var url = part). @Url.Action(url) implies the "url" is an action name, not a url Commented Mar 18, 2021 at 15:14

1 Answer 1

1

You're defining url in the JS on the client side. The Url.Action() call happens on the server side. The two cannot directly interact in the manner you're attempting.

The workaround in this case is to provide the Session["SpAccueilDefaut"] value directly to the Url.Action() as they are both held server side.

In addition, if the value in Session["SpAccueilDefaut"] is a string, which appears to be the case from the context it's used in later, then you need to delimit it using quotes in the JS if condition:

IdentificationSucces = function(data) {
  if ('@Session["SpAccueilDefaut"]') {
    window.location.href = '@Url.Action(Session["SpAccueilDefaut"].ToString())';
  } else {
    window.location.href = '@Url.Content("~/Intranet/Index")';
  }
};

As an aside, I'd suggest you research the difference between client side and server side programming. Understanding this is vital to developing web based technologies: What is the difference between client-side and server-side programming?

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

1 Comment

Thank, its work. I understand the 2nd part of your answer on understanding the difference between client side and server side. I say make a correction in the path to my project and no longer use @ Url.Action () and @ Url.Content (). (I don't have enough reputation to vote for the answer)

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.