【问题标题】:ASP.Net HiddenField value not updating when changed on client-sideASP.Net HiddenField 值在客户端更改时未更新
【发布时间】:2014-03-07 12:30:52
【问题描述】:

我有一个从代码隐藏调用的 JavaScript 函数,它既有输入参数又有返回值。我发现其他人需要类似的功能,并且他们被提供了一个 HiddenField 作为可能的解决方案。所以,这正是我想要做的——使用这样的控件来模拟函数值返回行为。

问题在于,一旦客户端单击按钮,我在代码隐藏中得到的只是该特定字段的先前值。第一次为空,下一次为“真”或“假”(作为字符串),具体取决于客户端选择的内容。 好吧,我不能使用以前的值,它必须是“实时的”。

我听说有人提到 AJAX 作为客户端和服务器之间通信的一种方式,但我不知道如何实现该解决方案。

我会根据您的要求提供更多信息。

标记(部分):

<body id="body">
    <form id="mainForm" runat="server">
        <asp:ScriptManager runat="server" ID="scriptManager" EnablePageMethods="true">
            <Scripts>
                <asp:ScriptReference Path="/jquery-2.1.0.js" />
                <asp:ScriptReference Path="/Dialog.js" />
            </Scripts>
        </asp:ScriptManager>
        <asp:HiddenField id="hfData" ClientIDMode="Static" runat="server" />
    </form>
</body>

JavaScript:

function deleteDialog(contact) {
    var response = confirm('Are you sure you want to delete the contact ' + contact + '?');
    var hiddenField = $('#hfData')[0]; // fetches the element as expected
    hiddenField.value = response.toString();
    alert(hiddenField.value); // prints correct values
}

代码隐藏:

Address addressDelete = addressService.fetchById(contactDelete.address_id);
string contactFullName = String.Join(" ", contactDelete.first_name, contactDelete.last_name);
Page.ClientScript.RegisterStartupScript(this.GetType(), "delete", "deleteDialog('" + contactFullName + "');", true);
Response.Write(hfData.Value); // I've also tried the Request.Form method but to no avail
contactService.delete(contactDelete);
addressService.delete(addressDelete);

【问题讨论】:

  • 当你想获取隐藏字段值时。在代码后面给客户端或客户端在代码后面。@Venom
  • @SumitPathak 在代码隐藏事件处理程序中有一个 Response.Write() 调用(仅用于测试目的) - 如果我正确理解您的评论。
  • 这段代码来自你的代码隐藏中的什么方法?
  • @RickS 我有一个 GridView 控件和一个位于该控件内的模板字段,其中包含一个 LinkBut​​ton,一旦单击它就会调用其事件处理程序。所以,你想知道的方法其实就是LinkBut​​ton的事件处理函数。
  • 在您从客户端获取隐藏值之前,您的服务器代码已经执行并完成了 Response.Write。我认为您对 ASP.NET 页面的流程感到困惑。

标签: c# javascript jquery asp.net hiddenfield


【解决方案1】:

试试这个

function deleteDialog(contact) {
var response = (confirm('Are you sure you want to delete the contact ' + contact + '?')) ? true : false;
var hiddenField = $("<%= hfData.ClientID %>").value; // fetches the element as expected
/*hiddenField.value = response.toString();*/
alert(hiddenField); // prints correct values
}

或检查:

  alert(document.getElementById("<%=hfData.ClientID%>").value);

【讨论】:

  • 如果我这样修改函数,它不会做任何事情。另外,我必须使用 jQuery 的获取机制,因为脚本是外部的,并且从父表单 (.aspx) 委托给用户控件 (.ascx)。
猜你喜欢
  • 2011-09-11
  • 1970-01-01
  • 2011-12-29
  • 1970-01-01
  • 2016-04-10
  • 2020-08-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多