asp.net passing values from JS/jquery to code behind c#

╄→尐↘猪︶ㄣ 提交于 2019-12-13 16:23:06

问题


I have tried "every" possible way of sending the screen.width vlaue from the JS script on the aspx page to the c# in the code behind and while I can see the screen.width being assigned correctly it never gets assigned to my hidden field value.

<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">

   <asp:HiddenField ID="hiddenfield" runat="server" />

   <script type="text/javascript" language="javascript">
       $(function(){ 
       $('#hiddenfield').val(screen.width); 
    });
    </script>

other content

</asp:Content>

and the code behind:

protected void btnChartGo_Click(object sender, EventArgs e)
{
   string s = hiddenfield.Value;
}

No matter what I try s is always ""

Something wrong with the above, everyone seems to be doing it like that and it works?


回答1:


This should get the right selector:

$('#<%= hiddenfield.ClientID %>').val(screen.width); 



回答2:


The ID of the rendered hidden field isn't "hiddenfield" - it'll be something like ctl00_bodycontent_hiddenfield.

Try using

$('[id$="hiddenfield"]') 

as the selector instead.




回答3:


<asp:HiddenField ID="hiddenfield" runat="server" ClientIDMode="Static">
</asp:HiddenField >

Make sure client ID mode of your hidden field is static if you are using ASP.NET 4 or use

$('#<%= hiddenfield.ClientID %>').val(screen.width); 



回答4:


Check the view source of the page and find out proper id of the element and then use jquery selector over it and then at the page load check for request.form collection to check if hidden variable is coming in post request or not



来源:https://stackoverflow.com/questions/11115365/asp-net-passing-values-from-js-jquery-to-code-behind-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!