Nirav Kamani
Nirav Kamani

Reputation: 3272

Action Link with Javascript and pass value to controller

I am using action link in my application.

I am having some requirement to call javascript on it's click event.

I know that I can do that using following code.

@Html.ActionLink("Home","Index","Main",new{@onclick="OnIndexCall"});

Now on the click event of action link I am computing two values in function and i also need to pass that values to the page in which I am redirecting.

I don't know how can I do that.

Please is there any way to pass the calculated value in from javascript function to redirection page?

EDIT :-

function OnIndexCall(){
    var a=10;
    var b=a+20;
}

Now i need to pass these "a" and "b" values to the redirection page.

Upvotes: 1

Views: 8576

Answers (2)

Sandip Rabade
Sandip Rabade

Reputation: 33

Create two hidden fields in form. assign values before submiting form may be on onClick event. so you will get those values in HttpPost action.

By this way your values will not be show in URL(Query String)

HTML

<a href="/Main/Index" onclick="return OnIndexCall(this)">Home</a>
<form type="post" action="URL" id="myform">
  <input type="hidden" name="a" id="a">
  <input type="hidden" name="b" id="b">
</form>

JavaScript

function OnIndexCall(elem){
    var a=10;
    var b=a+20;
    $("#a").val(a);
    $("#b").val(b);
    $("#myform").submit();
    return false;
}

Upvotes: 0

Kartikeya Khosla
Kartikeya Khosla

Reputation: 18873

You can pass data through QueryString as shown :-

@Html.ActionLink("Home","Index","Main",new{ @onclick="OnIndexCall(this)" });

function OnIndexCall(elem){
    var a=10;
    var b=a+20;
    $(elem).attr('href', $(elem).attr('href') + '?a=' + a + '&b=' + b);
}

Fiddle

Upvotes: 5

Related Questions