Хороший вопрос, я мог бы реализовать это и в моих проектах.
Я мог думать только об одном способе - используя 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>