enter image description here我的MVC5项目中有一个DropDownList和复选框。我想先收集数据,然后再通过AJAX提交给控制器。我可以使用哪种事件来代替按钮onclick="SaveList"
?现在,我使用此按钮提交
<div class="form-group pb-3" id="ddlEvent">
@Html.Label("Event", htmlAttributes: new { @class = "control-label font-weight-bold" })
@Html.DropDownList("EventID", new SelectList(Model.Events, "EventID", "DateDisplayCampus"), "Select Event", new { @class = "form-control" })
@Html.ValidationMessage("EventID", "", new { @class = "text-danger" })
</div>
@foreach (var item in Model.Programs) {
<p class="checkbox w-50 d-inline-block" id="programList">
<input type="checkbox" name="@item.ProgramName" id="[email protected]" />
<label for="[email protected]">@item.ProgramName</label> @*
<input name="@item.ProgramName" type="hidden" value="false" />*@
</p>
}
<button type="button" class="btn btn-danger" onclick="SaveList()">Save</button>
$(document).ready(function() {});
var SaveList = function() {
var SESSION_TIMES = [];
$("#programList input[id^=program]").each(function(index, val) {
debugger
var session = {};
var checkMajor = $(val).attr("name");
var isChecked = $(this).prop("checked");
if (isChecked) {
session = {
Major: checkMajor,
EventID: $("#EventID option:selected").val() //get EventId from dropdownlist
}
SESSION_TIMES.unshift(session); //add to the beginning of an array
}
debugger
});
// Ending of $("#programList input[id^=program]").each
//atleast if the sessiontTims array has an item, the going to ajax set the array to controller
if (SESSION_TIMES != 0) {
$.ajax({
url: "/SESSION_TIMES/SaveSessions", //controller/medthod
type: "POST",
data: {
list: JSON.stringify(SESSION_TIMES)
},
datatype: "json",
success: function(response) {
alert("Session saved")
window.location.href = '@Url.Action("Index", "SESSION_TIMES")';
},
error: function() {
alert('No Valid Data');
}
})
}
}
另一个选择是将事件绑定到表单提交;
form
标记内,我使用id myForm
type="submit"
替换按钮SaveList
转到功能$("#myForm").on("submit")
事件。<form id="myForm">
<div class="form-group pb-3" id="ddlEvent">
@Html.Label("Event", htmlAttributes: new { @class = "control-label font-weight-bold" })
@Html.DropDownList("EventID", new SelectList(Model.Events, "EventID", "DateDisplayCampus"), "Select Event", new { @class = "form-control" })
@Html.ValidationMessage("EventID", "", new { @class = "text-danger" })
</div>
@foreach (var item in Model.Programs)
{
<p class="checkbox w-50 d-inline-block" id="programList">
<input type="checkbox" name="@item.ProgramName" id="[email protected]" />
<label for="[email protected]">@item.ProgramName</label>
@*<input name="@item.ProgramName" type="hidden" value="false" />*@
</p>
}
<button type="submit" class="btn btn-danger">Save</button>
</form>
<script src="~/Scripts/jquery-3.4.1.min.js"></script>
<script>
$(document).ready(function () {
$("#myForm").on("submit",function(e){
e.preventDefault(); // this will stop the regular form redirect POST
SaveList(); // call SaveList
})
});
// turn SaveList to a function
function SaveList() {
var SESSION_TIMES = [];
// // checkboxElement
$("#programList input[id^=program]").each(function (index, val) {
debugger
var session = {};
//attr Id is a name of programName
var checkMajor = $(val).attr("name");
var isChecked = $(this).prop("checked");
if (isChecked) {
session = {
Major : checkMajor,
EventID: $("#EventID option:selected").val() //get EventId from dropdownlist
}
SESSION_TIMES.unshift(session); //add to the beginning of an array
}
debugger
});
// Ending of $("#programList input[id^=program]").each
//atleast if the sessiontTims array has an item, the going to ajax set the array to controller
//debugger
if (SESSION_TIMES != 0) {
$.ajax({
url: "/SESSION_TIMES/SaveSessions", //controller/medthod
type: "POST",
data: { list: JSON.stringify(SESSION_TIMES) },
datatype: "json",
success: function (response) {
alert("Session saved")
window.location.href = '@Url.Action("Index", "SESSION_TIMES")';
},
error: function () {
alert('No Valid Data');
}
})
} //Ending of if (SESSION_TIMES != 0)
} //Ending of SaveList
</script>
实现此目的的最佳实践方法是使用<form>
元素,然后将JS挂接到该表单的submit
事件。最佳实践是使用内插的事件处理程序,而不是内联onX
事件属性。
您的HTML也是无效的,因为在循环中重复了programList
元素上的p
id。 id
属性必须唯一,因此请将id
放在循环外部的元素上。
此外,您可以通过使用sessionTimes
和map()
选择器来改进创建:checkbox:checked
数组的逻辑。最后,sessionTimes
是一个数组,因此!= 0
检查永远不会为假。假设您正在尝试检查数组是否为空,请使用sessionTimes.length != 0
。
话虽如此,请尝试以下操作:
jQuery($ => {
$('#yourForm').on('submit', function(e) {
e.preventDefault();
var eventId = $("#EventID").val();
var sessionTimes = $('#programList input:checkbox:checked').map((i, el) => {
Major: el.name,
EventID: eventId
}).get().reverse();
if (sessionTimes.length != 0) {
$.ajax({
url: "/SESSION_TIMES/SaveSessions",
type: "POST",
data: {
list: JSON.stringify(sessionTimes)
},
datatype: "json",
success: function(response) {
window.location.href = '@Url.Action("Index", "SESSION_TIMES")';
},
error: function() {
alert('No Valid Data');
}
})
}
});
});
@using(Html.BeginForm("Action", "Controller", new { @id = "yourForm" ))
{
<div class="form-group pb-3" id="ddlEvent">
@Html.Label("Event", htmlAttributes: new { @class = "control-label font-weight-bold" })
@Html.DropDownList("EventID", new SelectList(Model.Events, "EventID", "DateDisplayCampus"), "Select Event", new { @class = "form-control" })
@Html.ValidationMessage("EventID", "", new { @class = "text-danger" })
</div>
<div id="programList">
@foreach (var item in Model.Programs) {
<p class="checkbox w-50 d-inline-block">
<input type="checkbox" name="@item.ProgramName" id="[email protected]" />
<label for="[email protected]">@item.ProgramName</label>
</p>
}
</div>
<button type="submit" class="btn btn-danger">Save</button>
})