Friday, November 1, 2013

Jquery - Pass asp button command argument with jquery


I have asp button:
<asp:button ID="btn1" runat="server" CommandArgument="" CssClass="btn1" OnClick="button_click"></asp:button>
and script:
$("a").click(function () {
            var val = $(this).attr('id').toString();                            
            $('.btn1').attr('CommandArgument',val);
            alert($('.btn1').attr('CommandArgument').toString());
            $('.btn1').click();
        });
after click it alerts me command argument. But on next step - when i trigger btn1 click with jquery it goes to codebehind and command argument is empty. Can i pass somehow command argument with jquery?
I've tried to save value to global variables but after postback they're all empty. And i don't want to use cookies or viewstate for that.
Thanks!
share|edit
 
I think that in dot 4 and up you can not change the command argument from javascript for security reasons - this arguments are part of the validation of the page and can not be change. I am not sure 100% but I think that you cant do that. Workaround add a hidden input field, change that value, and read that post value. –  AristosNov 20 '12 at 18:18 

3 Answers

CommandArgument is completely a server-side property and doesn't render any html attribute. So you can't change any button's attribute and fire click on it. The good news is that you can fire postback with client-side __doPostBack function and pass your custom value as second parameter:
<script type="text/javascript">
    $("a").click(function () {
        var val = $(this).attr('id').toString();
        __doPostBack("<%= btn1.UniqueID %>", val);
    });
</script>
And you can get passed argument in server click handler from the Request.Form collection:
protected void button_click(object sender, EventArgs e)
{
    var argument = Request.Form["__EVENTARGUMENT"];
}
If script above won't work then maybe __doPostBack function not defined on page. In this case add this code to Page_PreRender method: ClientScript.GetPostBackEventReference(btn1, string.Empty); this will force page to define __doPostBack method on page.
share|edit
 
Tried that but in my case it didn't go to codebehind. I triggered that click with another button. Quite obvious - they are asp buttons and do postback. My solution in the end was client side. I made input button with onlcick ="another_jquery_function()" to manage that val. Thanks for answer! –  Peeter Kõbu Nov 21 '12 at 7:24 
 
tnks!! this worked!! =D –  ch2o Dec 6 '12 at 15:27

No comments:

Post a Comment