简体   繁体   中英

Pass Javascript Variable into ASP.NET CommandArgument

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" />

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

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