0

I try to pass variable from jquery to code c# but something is wrong. I have in js this code:

<script type="text/javascript">
    var mySerial = '12345';
    var fooUrl = '@Url.Action("Foo", "Home")';
    window.location.href = fooUrl + '?mySerial' + encodeURIComponent(mySerial);
</script>

in controller :

[HttpPost]
public ActionResult Foo(string mySerial)
{
    return View();
}

After execution I keep this url: http://localhost:2214/@Url.Action("Foo",%20"Home")?mySerial12345 and I don't understand where's the problem, can someone help me?

1 Answer 1

3

You forgot the equal sign:

window.location.href = fooUrl + '?mySerial=' + encodeURIComponent(mySerial);

Notice mySerial= instead of mySerial.

By the way it seems that you are using the WebForms view engine and not Razor, at least that's the conclusion I draw if you see the @Url.Action literal in your generated output. If this is the case please use the proper syntax according to the view engine you are using:

<script type="text/javascript">
    var mySerial = '12345';
    var fooUrl = '<%= Url.Action("Foo", "Home") %>';
    window.location.href = fooUrl + '?mySerial=' + encodeURIComponent(mySerial);
</script>

Final remark: if this is in a separate javascript file you cannot use server side helpers such as Url.Action. It doesn't seem to be in a separate file because I can see the <script> inline tag but that's what you have shown here, maybe in your actual code this is in a separate file.

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

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.