rush2
rush2

Reputation: 33

Variable parameters not accepting in @Url.ACtion()

I am Passing two variable parameters in @Url.Action(). But its not accepting the variable parameters but accepting constant values. My code is like this

$(document).ready(function () {
    $(".print").click(function () {
        var id = $(#id).val();
        var dept = $(#dept ).val();
        var url = "@Html.Raw(@Url.Action("ActionResultname", "ControllerName", new {sid= id , sdept=dept }))";
        window.location.href = url;
    });
});

here id & sid is not accepting as a value , its taking as string . But if i pass like

var url = "@Html.Raw(@Url.Action("ActionResultname", "ControllerName", new {sid= 10, sdept=30}))";

Its accepting correctly as sid=10 & sdept=30. Please help me how to pass a variable to the parameter.

Upvotes: 1

Views: 2821

Answers (3)

Satpal
Satpal

Reputation: 133453

You can't pass JavaScript variable to Url.Action as it is execute on server side. further Url.Action function will render a string.

However, You can use generate url with static value and replace it with your input.

//Render Url with -1 and -2 value
var url = '@Url.Action("ActionResultname", "ControllerName", new { sid = -1, sdept= -2})'; 
url = url.replace(-1, id); //replace -1 with id
url = url.replace(-2, dept); //replace -2 with dept

window.location.href = url;

Upvotes: 3

Aravind Sivam
Aravind Sivam

Reputation: 1099

This not possible you need to append the query through client side try this

$(document).ready(function () {
    $(".print").click(function () {
        var id = $('#id').val();
        var dept = $('#dept').val();
        var url = '@Url.Action("ActionResultname", "ControllerName")';
        url += "?sid= " + id + "&sdept=" + dept;
        window.location.href = url;
    });
});

Upvotes: 1

Mō Iđɍɨɇƶ
Mō Iđɍɨɇƶ

Reputation: 331

In your case I would suggest just writing out the link you want as Razor code runs server-side so it won't get updated with the values you want. How about you change your code to:

$(document).ready(function () {
    $(".print").click(function () {
        var id = $(#id).val();
        var dept = $(#dept ).val();
        var url = "/ControllerName/ActionResultname?sid=" + id + "&sdept=" +dept;
        window.location.href = url;
    });
});

Upvotes: 1

Related Questions