如何在回发updatepanel后保留javascript变量?

时间:2013-07-20 15:30:23

标签: jquery asp.net updatepanel postback scope

用户更改触发updatepanel回发的select元素后,我试图在回发完成后将相同select的值设置为所选值,但不知何故我设置的值的值回发后会丢失一个隐藏的字段。

 function countrypostback() {
         $('#countryid').val($('select[name="countryselect"]').val());
         __doPostBack('upnlSearch', '');
     }

 $(document).ready(function () {
              $.ajax({
         type: "GET",
         url: "/service.svc/countries/",
         data: "",
         contentType: "application/json; charset=utf-8",
         dataType: "json",
         success: function (msg) {
             for (var i in msg) {
                 var resultitems = '<select onchange="countrypostback();" class="textbox" name="countryselect" id="countryselect">';
                 for (var i in msg) {
                     if (msg[i].name != '') {
                         resultitems += '<option value="' + msg[i].value + '">' + msg[i].name + '</option>';
                     }
                 }
                 resultitems += '</select>';
                 $('#countryselect').html(resultitems);
             }
         }
     });

    //here I'm trying to set the value of the dropdown to the value that was selected before the postback
     $("#countryselect").val($('#countryid').val());


    <input type="hidden" id="countryid" name="countryid" />

<asp:UpdatePanel ID="upnlSearch" runat="server">
<ContentTemplate>  


<span id="countryselect"></span>

</ContentTemplate> 
</asp:UpdatePanel>

我尝试在updatepanel的外部和内部放置隐藏字段countryid,但这没有什么区别,当我尝试通过

访问它时,我仍然有一个空的表单字段
$('#countryid').val()

我宁愿不使用viewstate(如果可能的话),因为增加了这个页面加载。

4 个答案:

答案 0 :(得分:1)

您可以访问服务器端(runat服务器)上的hiddenfield,然后您可以确保它再次写入页面。否则你有一些可能存储它客户端,但没有一个是那么漂亮。

答案 1 :(得分:0)

如果没有回发就会这么简单,你也可以使用event.preventDefault()阻止回发。我在微软的更新面板中发现的问题是服务器端代码总是在客户端代码之前执行,所以很难或几乎不可能阻止默认操作。一直以为这是愚蠢的和他们独特的ID,完全无法用jQuery选择任何东西。

$('select').on('change', function(ev){
  ev.preventDefault();
  alert($(this).val());
});

http://jsfiddle.net/NtzRC/1/

答案 2 :(得分:0)

这可能会帮助你到那儿。

    <script type="text/javascript">
    // execute script once
    [javascript code]
    // register script with PageRequestManager for partialpostback "reset value of control"
    if(typeof(Sys)!=='undefined'){
    if(typeof(Sys.WebForms)!=='undefined'){
    if(typeof(Sys.WebForms.PageRequestManager)!=='undefined'){
    var prm = Sys.WebForms.PageRequestManager.getInstance();
    prm.add_endRequest(function(){
    [javascript code]
    });
    }
    }
    }
    </script>

答案 3 :(得分:0)

e.preventDefault();是理想的解决方案,尤其是在使用JQuery和。时 阿贾克斯。下面是一个按钮单击事件的示例,它在JQuery中执行错误处理 使用ASP.NET必填字段然后将数组发布到.aspx页面上的Web服务 它返回一个要保存在hiddenfield控件中的值。一旦网络服务 返回要存储在隐藏字段中的值,完整的函数显示 基于成功分配的布尔值的标签中的成功消息 功能。这是我的例子。

$(document).ready(function () {
 $("#<%=btnApply.ClientID %>").click(function (e) {
  var formtitle = $("#<%=txtFormTitle.ClientID %>");
  var email = $("#<%=txtEmail.ClientID %>");
  var tdform = $("#trform .tdform");
  var formId = $("#<%=hdnFormTemplateID.ClientID %>");
  var statuslabel = $("#<%=lblStatus.ClientID %>");
  var successful = false;
  statuslabel.html("");

      if (!formtitle.val() || !email.val()) {
      statuslabel.css("color", "#CC3300");
      statuslabel.html("The following fields are invalid!");
      return false;
      }
  else {
     $.ajax({
    type: "POST",
    url: "FormBuilder.aspx/GetFormElements",
    traditional: true,
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    data: JSON.stringify({ columnone: firstColumn, columntwo: secondColumn, title: formtitle.val(), emailaddress: email.val(), form: tdform.html(), formId: formId.val() }),
    success: function (data) {
      var id = $("#<%=hdnFormTemplateID.ClientID %>")
      id.val(data.d);
      successful = true;
    },
    error: function (err) {
      err = "Did not work";
      alert(err);
    },
    complete: function () {
       if (successful) {
         var statuslabel = $("#<%=lblStatus.ClientID %>");
                 statuslabel.html("");                                       
         statuslabel.css("color", "#92aa6c");
         statuslabel.html("Successfully Updated");

    }
    }
});
e.preventDefault();
  }
});
});
Here is the web service sub procedure.  I always find it helpful to have someone post 
VB.NET code and I will do so more in the future for those who prefer to work in 
VB.NET.
Imports System.Web.Services
Imports System.Web.Script.Services
Imports System.Data.SqlClient

<ScriptService()>
Public Class FormBuilder
 Inherits System.Web.UI.Page
 Public Shared formTemplateId As Integer


<WebMethod()> _
Public Shared Function GetFormElements(columnone As List(Of String), columntwo As 
  List(Of String), title As String, emailaddress As String, form As String, formId As 
  String) As String 
  Dim strconn As String = ConfigurationManager.AppSettings("ConnectionString")
  Dim conn As New SqlConnection(strconn)
  Dim mycommand As New SqlCommand
  Dim retVal As Integer = 0
  Dim itemOne As String = String.Empty

  'mylogic to begin storing the data in the database using a For Loop'
  If columnone.Count > 0 Then
    For i As Integer = 0 To columnone.Count - 1 Step 1
        itemOne = Regex.Replace(columnone(i).ToString, "\s", "")
    Next
  End If


  Return retVal.ToString

 End Function

结束班