我們有一個串列必須查看為
@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 方法的過載。
我們能以任何方式實作這種場景嗎?
uj5u.com熱心網友回復:
好問題,我也可以在我的專案中實作這一點。
我只能想到一種方法——使用javascript,提交表單時,先洗掉其他表單輸入欄位,然后重新提交表單。
首先,我們需要將輸入欄位放在div帶有類的父級input-container中,這樣我們就可以通過洗掉整個欄位來快速洗掉所有欄位div。我還在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 模型系結必須以 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>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/416089.html
標籤:
