我在 asp.net 应用程序中有一个 apsx 页面,其元素是根据用户的输入使用 javascript 构建的。当用户单击“保存”按钮时,我需要在服务器上创建一个文件,其中包含用户提供的所有数据。问题是该数据存储在 javascript 中(在生成的 div 中)。我需要以某种方式将此数据放入 asp.net 按钮单击函数或以所有数据作为参数调用该函数。如何实现?
最佳答案
您始终可以尝试在表单上的隐藏输入字段中弹出所需的数据,因此您可以使用 Request.Form["fieldName"]
访问它(只需记住提供隐藏输入字段“名称”属性,否则您将花费不必要的时间试图找出为什么无法通过代码隐藏中的 Request.Form :P) 访问它。这可能是实现这一目标的最简单方法......
编辑
只是为了让您快速了解一下,这里是我的一个项目中的一些示例代码,我在其中根据某些动态字段生成隐藏的输入字段,以便在 Save()
函数执行后回发到服务器从某些按钮/ anchor 调用:
function Save() {
$("div.fieldcontainer span.readonly").each(function () {
var fieldId = $(this).attr("id");
var fieldValue = $(this).html();
var ctrl = $("<input type=\"text\" id=\"" + fieldId + "\" name=\"" + fieldId + "\" style=\"display:none;\" />");
ctrl.val(fieldValue);
$(this).parent().append(ctrl);
});
$("div.fieldcontainer a.attachment").each(function () {
var fieldId = $(this).attr("id");
var fieldValue = $(this).text() + "|" + $(this).attr("href");
var ctrl = $("<input type=\"text\" id=\"" + fieldId + "_txtHiddenValue\" name=\"" + fieldId + ":txtHiddenValue\" style=\"display:none;\" />");
ctrl.val(fieldValue);
$(this).parent().append(ctrl);
});
$("div.fieldcontainer select").each(function () {
var fieldId = $(this).attr("id");
var fieldValue = $(this)[0].value;
var fieldText = $(this).find("option[value='" + fieldValue + "']").text().replace("<", "").replace(">", "");
$(this).attr("id", fieldId + "_ORIGINAL");
var ctrl = $("<input type=\"text\" id=\"" + fieldId + "\" name=\"" + fieldId + "\" style=\"display:none;\" />");
ctrl.val(fieldText + "$" + fieldValue);
$(this).parent().append(ctrl);
});
$("div.fieldcontainer input[type='checkbox']").each(function () {
var fieldId = $(this).attr("id");
var fieldValue = $(this).attr("checked");
$(this).attr("id", fieldId + "_ORIGINAL");
var ctrl = $("<input type=\"text\" id=\"" + fieldId + "\" name=\"" + fieldId + "\" style=\"display:none;\" />");
ctrl.val(fieldValue);
$(this).parent().append(ctrl);
});
document.form1.submit();
}
您可以实现相同类型的逻辑来循环遍历每个客户端生成的 DIV,并在提交表单之前为每个 DIV 创建一个隐藏输入。这样,当用户忙于与之交互时,您就不会因为过多的额外标记而不必要地使页面陷入困境......
关于javascript - 从 ASP.NET 应用程序中的 javascript 获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9207464/