简体   繁体   中英

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.

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

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM