我们有一个绑定(bind)查看的列表
@model List<DataModels.UseCase>
此 View 包含 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();
}
请注意- 例如,我仅在表单上显示了复选框控件,还有其他一些控件。
现在,在本例中,例如 View 包含 10 条记录,但 10 条记录中仅选择了 2 条,那么我们只需将 2 条选定记录传递给 POST 方法,而不是全部 10 条。这是为了减少 POST 方法的过载。
我们可以通过任何方式实现这种类型的场景吗?
最佳答案
问得好,我也可以在我的项目中实现这一点。
我只能想到一种方法——使用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" >
}
我们需要将一个事件绑定(bind)到您的表单。在表单提交时,我们需要识别哪个 targetCheckbox
没有被选中,然后删除包含它们的div。 我们还需要替换输入字段的索引,因为 ASP.NET MVC 模型绑定(bind)必须以 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>
关于c# - 如何仅发布 MVC 列表中选定的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61443679/