【发布时间】:2018-04-07 19:53:38
【问题描述】:
您好,我创建了在按钮单击时添加多个下拉列表的逻辑。下面是我的查看代码
<body>
@using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
<input id="btnAdd" type="button" value="Add" onclick="AddTextBox()" />
<br />
<br />
<div id="DropdownContainer">
<!--Textboxes will be added here -->
</div>
<br />
<input type="submit" value="Submit" />
}
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
function GetDynamicTextBox(value) {
var div = $("<div />");
var textBox = '<div class="col-xs-2"><select name="From" class="form-control">';
textBox = textBox + '<option value="">From</option>';
textBox = textBox + '<option value="1 AM">1 AM</option>';
textBox = textBox + '<option value="1.30 AM">1.30 AM</option>';
textBox = textBox + '<option value="2 AM">2 AM</option>';
textBox = textBox + '<option value="2.30 AM">2.30 AM</option>';
textBox = textBox + '</select></div>';
textBox = textBox + '<div class="col-xs-2"><select name="To" class="form-control">';
textBox = textBox + '<option value="">To</option>';
textBox = textBox + '<option value="1 AM">1 AM</option>';
textBox = textBox + '<option value="1.30 AM">1.30 AM</option>';
textBox = textBox + '<option value="2 AM">2 AM</option>';
textBox = textBox + '<option value="2.30 AM">2.30 AM</option>';
textBox = textBox + '</select> </div>';
//textBox.val(value);
div.append(textBox);
var button = $("<input />").attr("type", "button").attr("value", "Remove");
button.attr("onclick", "RemoveTextBox(this)");
div.append(button);
return div;
}
function AddTextBox() {
var div = GetDynamicTextBox("");
$("#DropdownContainer").append(div);
}
function RemoveTextBox(button) {
$(button).parent().remove();
}
$(function () {
var values = eval('@Html.Raw(ViewBag.Values)');
if (values != null) {
$("#DropdownContainer").html("");
$(values).each(function () {
$("#DropdownContainer").append(GetDynamicTextBox(this));
});
}
});
</script>
@if (ViewBag.Message != null)
{
<script type="text/javascript">
$(function () {
alert("@ViewBag.Message")
});
</script>
}
</body>
我的控制器端得到调用是
[HttpPost]
public ActionResult Index(string[] DynamicTextBox)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
ViewBag.Values = serializer.Serialize(DynamicTextBox);
string message = "";
foreach (string textboxValue in DynamicTextBox)
{
message += textboxValue + "\\n";
}
ViewBag.Message = message;
return View();
}
但是当我点击提交时,我无法获得两个被选中的下拉值。
我需要为所有选择的多个下拉值获取值,以及如何放置 验证下拉 id 没有选择。
在提交点击时,我需要将选定的下拉列表值保存在数据库中。
验证码是
function validate() {
var values = [];
$('#DropdownContainer option').each(function () {
var e = $(this);
console.log(e);
return false;
});
return false;
}
如何获得选定的值?
【问题讨论】:
标签: c# asp.net-mvc asp.net-mvc-4 asp.net-mvc-3