[RESOLVED]checkboxfor bind to model ajax postback

hi,

I am trying to get checkboxfor checked values through ajax postback in my controller but it is giving me false even if checkbox is checked in the view before clicking the button control.

my code looks like this:

[HttpPost]
public ActionResult CivilSurveys(CivilSurveyViewModel modelData)
{
try
{
var s = Request["SurveyAccepted"].Contains("true");
if (modelData.SurveyAccepted)
{
modelData.SurveyAcceptedBy = int.Parse(Session["SessionUserId"].ToString());
modelData.SiteDiagram = ViewBag.Image;
modelData = (BAL.Surveys.GetCivilSurvey(modelData));
}
return View(modelData);
}
catch (Exception ex)
{
Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
return View();
}
}

@using (Html.BeginForm("", "", FormMethod.Post, new { id = "frmCivilSurveys" }))
{

<div class="ControlSet">
@Html.LabelFor(model => model.SurveyAcceptedBy):
@Html.CheckBoxFor(model => model.SurveyAccepted, new { style = "margin-left: 198px;" })

</div>

<div style="clear: both; margin: 10px; padding-top: 10px; overflow: hidden;">

<input type="submit" class="k-button" value="Create" style="float: right;" id="btnCreateCivilSurvey" />
<input type="button" class="k-button" value="Update" id="btnEditCivilSurvey" style="float: right;" />
</div>

 <script>

$("#btnCreateCivilSurvey").click(function() {
if ($("#frmCivilSurveys").valid()) {

$.ajax({
type: "POST",
url: "@Url.Action("CivilSurveys", "Civils")",
data: JSON.stringify($(‘#frmCivilSurveys’).serializeObject()),
dataType: "json",
contentType: "application/json; charset=utf-8",
async: true,
cache: false,
success: function (msg) {
if (msg.status == "1") {
}
alert(msg.message);

}
});

}
else {

$($("#frmCivilSurveys").validate().errorList[0].element).focus();
}
return false;
});

  </script>

please reply back if some one has a solution to it.

Put type "button" instead "submit".

<input type="submit" class="k-button" value="Create" style="float: right;" id="btnCreateCivilSurvey" />

it was becuse of hidden field that was autocreated while using checkboxfor.

I have resolved this issue by using input of type checkbox and mannually setting id,s for them in foreach loop like this:

@foreach (var item in Model.SurveyTypeList)
{
@Html.Label(item.Text)
<input name="SurveyTypeList[@i].Text" type="hidden" value="@item.Text" />
<input name="SurveyTypeList[@i].Value" type="hidden" value="@item.Value" />
<input data-val="true" id="SurveyTypeList@(i)__IsSelected" name="SurveyTypeList[@i].IsSelected" style="margin-right: 200px; float: right" type="checkbox" value="true" />
<br /><br />
i++;
}

Leave a Reply