Hello
In my mvc form I have many checkboxes and textboxes which are being dinamycally generated. It works perfect for the checkboxes it passes only that are selected. But for the textboxes it passes all the values. When I debug in my console I see Array [45,55] , I mean it gets only the textboxes that are filled but in controller passes all values even those with 0. Any idea? thank you
What I have tried:
My View
@foreach (var item in Model.SubCategory.Where(x => x.CategoryID == "05"))
{
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<input class="col-sm-1" type="checkbox" id="@item.SubCategoryID" name="Subcategory" value="@item.SubCategoryID" />
<label class="col-sm-10" for="optionId">@item.SubCategoryDescription</label>
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Details.Ammount, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-2">
@Html.TextBoxFor(model => model.Details.Ammount, new { @class = "ammount", Name = "ammount" } )
@Html.ValidationMessageFor(model => model.Details.Ammount, "", new { @class = "text-danger" })
</div>
</div>
</div>
My srcipt
<script type="text/javascript">
$(document).ready(function () {
$('#postBtn').on('click', function (e) {
var ammounts = [];
$('input[name="Subcategory"]').each(function () {
if ($(this).is(':checked') === true) {
var amountField = $(this).parent().parent().next().find("input[name='ammount']");
if ($(amountField).val() !== '') {
if (parseInt($(amountField).val()) > 0) {
ammounts.push(parseInt($(amountField).val()));
}
}
}
});
console.log(ammounts);
$.ajax({
url: '@Url.Action("Create", "Budgets")',
type: "POST",
data: JSON.stringify({
Subcategory: [],
ammount: ammounts
}),
dataType: "json",
traditional: true,
success: function () {
alert("ajax request to server succeed");
},
});
});
});
</script>
My controller
public JsonResult Create(IEnumerable<int> Subcategory, IEnumerable<decimal> ammount)