Reputation: 1131
I've already tried everything i know, but still can't get my checkboxlist checked values. I have a nested partial view that render some client info data and allows him to do some inserting. Nothing complicated. However, there's a dynamic list of contracts that is generated for some kind of clients. This is my checkboxlist, the dynamic list. While i can get the entire form values, i cannot get any check values from my checkboxes.
Here´s my code:
ViewModel
public List<TITAContratos> Contratos { get; set; }
public class TITAContratos
{
public string NumContrato { get; set; }
public bool Checked { get; set; }
}
VIEW
<div style="position: static; float: left;" id="debPropContratos">
<span>Contratos do Cliente:</span>
@Html.EditorFor(item => item.Contratos)
EDITOR
@model MVCGestaoWeb.Models.ViewModels.TITAContratos
<p>
@Html.HiddenFor(x => x.NumContrato)
@Html.CheckBoxFor(x => x.Checked )
@Html.LabelFor(x => x.Checked , Model.NumContrato)
<br />
</p>
SCRIPT
$("#btnCadAcordo").click(function () {
var urlSave = '@Url.Action("DebPropostas")';
var taVM = $("#debPropForm").serializeObject();
$.ajax({
type: "POST",
url: urlSave,
//Com isso ele permite a passagem de objetos para o Controller
data: JSON.stringify(taVM),
datatype: "JSON",
contentType: "application/json; charset=utf-8",
success: function (returndata) {
$("#containerDebProp").html(returndata);
}
});
return true;
});
$.fn.serializeObject = function () {
var o = {};
var a = this.serializeArray();
$.each(a, function () {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
EDIT
Just to point the problem: i can't get any checkbox checked value. Even though i can get my checkboxes hidden value, i cannot get which checkboxes were checked.
Upvotes: 2
Views: 6761
Reputation: 1038710
That's because of the additional hidden field generated for each checkbox by the CheckBoxFor
helper.
How about sending normal application/x-www-form-urlencoded
encoded request using the .serialize()
method instead of JSON:
$("#btnCadAcordo").click(function () {
var urlSave = '@Url.Action("DebPropostas")';
$.ajax({
type: 'POST',
url: urlSave,
data: $('#debPropForm').serialize(),
success: function (returndata) {
$('#containerDebProp').html(returndata);
}
});
return true;
});
This way you no longer need the serializeObject
function. Also the debPropForm
is nowhere to be seen in the code you have shown, make sure this form wraps the editor template and its input fields.
Upvotes: 2