0

It doesn't look like this is possible, but is there any way to pass a javascript variable into the CommandArgument field? I'm trying to pass the facility_id variable so that the code behind can access the value.

Here is my aspx code:

<script type="text/javascript">
    var facility_id = 50;
</script>
<asp:Button CssClass="btn btn-primary btn-lg" ID="submitBtn" runat="server" Text="Create EDD" CommandArgument='<% facility_id.Value %>' OnClick="submitBtn_Click" />
John Doe
  • 1,950
  • 9
  • 32
  • 53

1 Answers1

0

As you expect, the CommandArgument is a server-side property of Button server control and you can't assign it from client-side code because it does not render corresponding HTML attribute. However, you can set up a postback from client-side with __doPostBack() function as provided below:

<script>
    var facility_id = 50;

    $('#something').click(function () {
        __doPostBack("<%= submitBtn.UniqueID %>", facility_id);
    });
</script>

Code behind

protected void submitBtn_Click(object sender, EventArgs e)
{
    // assumed 'facility_id' is an int? or Nullable<int> property,
    // make sure the event argument is parseable to integer value
    var evArg = int.Parse(Request.Form["__EVENTARGUMENT"]);
    facility_id = evArg;
}

If you cannot use __doPostBack() function because it is undefined on the page, then you can handle PreRender event of that page and provide GetPostBackEventReference() method:

protected void Page_PreRender(object sender, EventArgs e)
{
    ClientScript.GetPostBackEventReference(submitBtn, string.Empty);
} 
Tetsuya Yamamoto
  • 24,297
  • 8
  • 39
  • 61