I am not able to save the checked checkbox id to database. Model class is
public partial class Mapping
{
public int Id { get; set; }
public Nullable<int> DistrictId { get; set; }
public Nullable<int> PostId { get; set; }
public List<string> GetAllSelctedCheckBoxes { get; set; }
}
except
public List<string> GetAllSelctedCheckBoxes { get; set; }
all other fields bind to database.
view page is
<div class="form-group">
@Html.Label("District", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("DistrictId", ViewBag.DistrictId as SelectList, "-- Please Select --", new { style = "width:250px" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.PostId,"PostName", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
<div id="PostMaster"></div>
@Html.HiddenFor(m => m.GetAllSelctedCheckBoxes)
@Html.ValidationMessageFor(model => model.PostId, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" id="Create"/>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("#DistrictId").change(function () {
$("#PostMaster").empty();
$.ajax({
type: 'POST',
url: '@Url.Action("GetPosts")',
dataType: 'json',
data: { id: $("#DistrictId").val() },
success: function (posts) {
$.each(posts, function (i, post) {
$("#PostMaster").append('<input type="checkbox" name="postdata" value=' + post.Text + '>' + post.Text + '<br>');
});
},
error: function (ex) {
alert('Failed to retrieve post.' + ex);
}
});
return false;
})
});
</script>
<script>
$("#Create").click(function () {
$('#GetAllSelctedCheckBoxes').empty();
debugger;
var getList = [];
$("#PostMaster input:checked").each(function () {
getList.push($(this).val());
var form = ($(this).val());
});
$('#GetAllSelctedCheckBoxes').val(getList);
});
</script>
this is my view page, here I can check the checkbox and the selected checkbox is displayed in
GetAllSelctedCheckBoxes
and this is passing to the httpPost parameter of the controller.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Create(Mapping mapping)
{
if (ModelState.IsValid)
{
db.Mappings.Add(mapping);
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
return View(mapping);
}
but I am not able to store the selected value to db . can sombody please help me to get solution that the selected item will display as string and I need to save it as interger.
What I have tried:
I have tried many times and cannot find a solution correctly for my problem