[英]How to post only selected items from list in MVC
我們有一個列表必須查看為
@model List<DataModels.UseCase>
此視圖包含 html 形式為
@using (Html.BeginForm())
{
for (int i = 0; i < Model.Count(); i++)
{
@Html.CheckBoxFor(m => Model[i].IsSelected)
//few other controls as
}
<input type="submit" value="Submit Selection" >
}
而在 Controller 中,POST 方法如下所示
[HttpPost]
public ActionResult payment([Bind(Include = "Id,IsSelected// few other properties")] List<UseCase> useCases)
{
// Few business logic
return View();
}
請注意- 例如,我只在表單上顯示了復選框控件,還有其他幾個控件。
現在,在這種情況下,例如視圖包含 10 條記錄,但在 10 條中只有 2 條被選中,那么我們只需將 2 條選定的記錄傳遞給 POST 方法,而不是全部 10 條。這是為了減少 POST 方法的過載。
我們能以任何方式實現這種場景嗎?
好問題,我也可以在我的項目中實現這一點。
我只能想到一種方法——使用javascript,在提交表單時,先刪除其他表單輸入字段,然后重新提交表單。
首先,我們需要將輸入字段放在帶有 class input-container
的父div
中,因此我們可以通過刪除整個div
來快速刪除所有字段。 我還在您的輸入字段中添加了一個 class targetCheckbox
,以便我們可以將一個事件附加到它;
@using (Html.BeginForm())
{
for (int i = 0; i < Model.Count(); i++)
{
<div class="input-group">
@Html.CheckBoxFor(m => Model[i].IsSelected, new { @class="targetCheckbox" })
//few other controls as
<div class="input-group">
}
<input type="submit" value="Submit Selection" >
}
我們需要將一個事件綁定到您的表單。 在表單提交時,我們需要確定哪些targetCheckbox
沒有被選中,然后刪除包含它們的 div。 我們還需要替換輸入字段的索引,因為 ASP.NET MVC model 綁定必須以 0 開頭並且不應跳過。 畢竟重新提交表格;
<script>
$(document).ready(function(){
$("form").submit(function(e){
e.preventDefault();
var index = 0;
// loop through all the checkbox
$(".targetCheckbox").each(function(){
if($(this).is(":checked")){
// get the parent
var parent = $(this).closest(".input-container");
// loop through all the input fields inside the parent
var inputFieldsInsideParent = $(parent).find(":input");
// change the index inside the name attribute
$(inputFieldsInsideParent).each(function(){
var name = $(this).attr("name");
var firstBracket = name.IndexOf("[");
var secondBracket = name.IndexOf("]");
if(firstBracket != null && secondBracket != null){
// check if this is a valid input field to replace
var newName = name.substring(0,firstBracket)+index+name.substring(secondBracket);
// result should be IntputFieldName[newIndex].Property
// assign the new name
$(this).attr("name",newName);
}
});
index++;
}else{
// empty the parent
$(this).closest(".input-container").html("");
}
});
// submit the form
$(this).submit();
});
});
</script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.