我正在使用ASP在下拉框中查找所选值。下拉框选项在加载时生成。以下是JavaScript:
function CreateDepartmentDropdown(data) {
var dropdown = document.getElementById("department_dropdown");
for (var i = 0; i < data.length; i++) {
var array = data[i].split(',');
var option = document.createElement("option");
option.value = array[0];
option.innerHTML = array[1];
dropdown.add(option);
}
}
它看起来像这样:
对我来说很好看。然后我也检查了HTML以确定:
看起来也很棒。现在问题就出现了。当我按下提交时,这个代表在C#中激活(仍然只在进行测试时):
void Activity_Submit_Click(object sender, EventArgs e)
{
int fye = Int32.Parse(fye_dropdown.Value);
String activity_name = activity_name_field.Value;
String activity_responsible = responsible_field.Value;
int department = Int32.Parse(department_dropdown.Value);
String activity_start = datepicker_start.Value;
String activity_end = datepicker_end.Value;
}
当我调试它时,它停在部门说它的格式不正确。在即时窗口中查看department_dropdown.Value
会显示一个空字符串,而下拉列表本身则有0个孩子。
为什么当清单明显存在时,这会返回空响应?我该如何解决这个问题?
答案 0 :(得分:1)
客户端项目不会像这样回发到服务器。
最简单的方法是将数组序列化为Json,将其放在hidden
输入元素中value
:
在你的标记中:
<asp:HiddenField runat="Server" ID="department_dropdown_items" cssclass="department_dropdown_items" />
<asp:HiddenField runat="Server" ID="department_dropdown_selected" cssclass="department_dropdown_selected" />
您的Javascript:
function CreateDepartmentDropdown(data) {
var dropdown = document.getElementById("department_dropdown");
for (var i = 0; i < data.length; i++) {
var array = data[i].split(',');
var option = document.createElement("option");
option.value = array[0];
option.innerHTML = array[1];
dropdown.add(option);
}
$(".department_dropdown_items").text(JSON.Stringify(data));
}
$(document).ready(function() {
$("form").submit(function(e) {
$(".department_dropdown_selected").text( $("#department_dropdown").value);
});
});
然后在后面的代码中使用它:
void Activity_Submit_Click(object sender, EventArgs e)
{
string[] data = new JavascriptSerializer().Deserialize<string[]>(department_dropdown_items.Value);
string selectedValue = department_dropdown_selected.Value;
int fye = Int32.Parse(fye_dropdown.Value);
String activity_name = activity_name_field.Value;
String activity_responsible = responsible_field.Value;
int department = Int32.Parse(department_dropdown.Value);
String activity_start = datepicker_start.Value;
String activity_end = datepicker_end.Value;
}
代码未经过测试。告诉我它是否不起作用:))
答案 1 :(得分:0)
所以我最终做了以下事情:
department_dropdown_selected_value
function GetDepartmentDropdownValue(sel) {
var hidden_field = document.getElementById('department_dropdown_selected_value');
hidden_field.value = sel.value;
}
<select class="form-control" id="department_dropdown" onchange="GetDepartmentDropdownValue(this)">
int department = Int32.Parse(department_dropdown_selected_value.Value);