[英]JQuery in MVC - Send form data as array with getJson
我有一個MVC視圖,該視圖通過使用getJSON定期指向控制器中的方法並解析返回的Json來更新頁面上的元素。
控制器中的方法藍圖:
public JsonResult GetAttendeeJson()
{
//Code which creates the Json I need.
return Json(result, JsonRequestBehavior.AllowGet);
}
從視圖致電:
function showDetects() {
// This is the main AJAX that retrieves the data.
$.getJSON('/Attendee/CardDetections', function (data) {
$.each(data, function (i, country) {
// perform actions using data.
});
});
}
了解我在做什么並不重要,但是我的情況已經改變,並且現在我在視圖中添加了一個包含可變數量的復選框的表單(取決於使用該頁面的用戶,復選框的數量會有所不同)。
復選框表單創建:
<form onsubmit="@Url.Action("Index", "Attendee")" method="post" id="checkboxform">
@{int i = 0;}
@{foreach (string s in ViewBag.LocationNames)
{
<div class="radio-inline">
@s
<input class="checkboxcontrol" onchange="this.form.submit()" type="checkbox" id="CheckBoxes" name="CheckBoxes" value="@ViewBag.LocationIds[i]">
</div>
i++;
}
}
</form>
這種形式的添加意味着我現在需要我的控制器方法,該方法返回Json以便能夠使用這些復選框的數據。 現在, GetAttendeeJson
需要知道當前在表單上選中了哪些復選框。
所以我希望方法藍圖像這樣:
public JsonResult GetAttendeeJson(int[] checkBoxValues)
{
//Code which creates the Json I need using the checkbox values.
return Json(result, JsonRequestBehavior.AllowGet);
}
是否可以不提交表格就這樣做? 我使用提交做其他事情,導致重新加載頁面。 我使用getJson來更新頁面內容。
理想情況下,我只想獲取數組中已選中復選框的“值”字段,然后在調用它時將其作為參數發送給GetAttendeeJson
函數。
謝謝,JK
假設您有以下HTML-
<input type="checkbox" name="chk" value="1" /> 1
<input type="checkbox" name="chk" value="2" /> 2
<input type="checkbox" name="chk" value="3" /> 3
<input type="checkbox" name="chk" value="4" /> 4
<input type="button" id="submit" value="Submit"/>
然后,我們可以使用AJAX POST
將選中的復選框推送到一種操作方法,如下所示-
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script>
$(function () {
$("#submit").click(function () {
var vals = [];
$('input:checkbox[name=chk]:checked').each(function () {
vals.push($(this).val());
});
$.ajax({
url: "/Home/GetAttendeeJson",
type: "post",
dataType: "json",
data: JSON.stringify({ checkBoxValues: vals }),
contentType: 'application/json; charset=utf-8',
success: function (result) {
if (result.success) {
}
else {
}
}
});
});
});
</script>
當我們點擊按鈕時,選中的復選框可通過以下控制器操作獲得-
public JsonResult GetAttendeeJson(int[] checkBoxValues)
{
//Code which creates the Json I need using the checkbox values.
return Json("true", JsonRequestBehavior.AllowGet)
}
如下查看渲染圖,我們可以在其中選中/取消選中復選框-
然后,當您放置斷點並調試代碼時,輸出將如下所示-
嘗試定期觸發ajax調用。 這樣,您無需提交表格就可以將其發送給您的函數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.