[英]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.