athira k

athira k

  • NA
  • 140
  • 53.8k

save multiple selected checkbox value to database mvc

Apr 10 2017 3:05 AM
I am developing an MVC project and I have the task to select more than one item in checkbox and want to save these selected item to database. For this I have created three table. First one is DistrictMaster
 
public partial class DistrictMaster
{
   public int Id { get; set; }
   public string DistrictName { get; set; }
   public virtual ICollection<PostMaster> PostMasters { get; set; }
}
 
Here Iam entering various districts and this saves to database second table PostMaster
 
public partial class PostMaster
{
   public int Id { get; set; }
   public string PostName { get; set; }
   public string PIN { get; set; }
   public Nullable<int> DistrictID { get; set; }
   public virtual DistrictMaster DistrictMaster { get; set; }
}
 

here I am entering different post based on the district selected from drop down list . The DistrictID is Foreign key and will save the pincode and names to the corresponding district in table

The third table is AgentPostMapping

public partial class AgentPostMapping
{
   public int Id { get; set; }
   public Nullable<int> AgentId { get; set; }
   public Nullable<int> PostId { get; set; }
   public Nullable<System.DateTime> EffectDate { get; set; }
}
 
 

Here the PostId is not foreign key and I need to save the selected or checked items in checkbox as interger to this postId. This is the part where Iam trouble in doing.

controller

  
public ActionResult Create()
{
  ViewBag.AgentId = new SelectList(db.AgentMasters, "ID", "FirstName");
  ViewBag.DistrictId = new SelectList(db.DistrictMasters, "Id", "DistrictName");
  return View();
}
 
public JsonResult GetPosts(string id)
{
   List<SelectListItem> posts = new List<SelectListItem>();
   var postList = this.Getpost(Convert.ToInt32(id));
   ViewBag.Postdata= this.Getpost(Convert.ToInt32(id));
   var postData = postList.Select(m => new SelectListItem()
   {
       Text = m.PostName,
       Value = m.Id.ToString(),
   });
   return Json(postData, JsonRequestBehavior.AllowGet);
}
 
 
public IList<PostMaster> Getpost(int DistrictId)
{
    return db.PostMasters.Where(m => m.DistrictID == DistrictId).ToList();
}
 
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Create([Bind(Include = "Id,AgentId,PostId,EffectDate")] AgentPostMapping agentPostMapping, FormCollection formdata)
{
    if (ModelState.IsValid)
    {
       db.AgentPostMappings.Add(agentPostMapping);
       await db.SaveChangesAsync();
      return RedirectToAction("Index");
     }
    ViewBag.AgentId = new SelectList(db.AgentMasters, "ID", "FirstName", agentPostMapping.AgentId);
    return View(agentPostMapping);
}
 
 
 

This is my controller part And I didn't write the code in [HttpPost]. Can anyone please help me to write code to save to db.

view(create)

<div class="form-group">
@Html.LabelFor(model => model.AgentId,"AgentName", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("AgentId", null, "select", htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.AgentId, "", new { @class = "text-danger" })
</div>
</div>
 
 
 
<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.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" />
</div>
</div>
</div>
}
 
 
<script type="text/javascript">
$(document).ready(function () {
//District Dropdown Selectedchange event
$("#DistrictId").change(function () {
$("#PostMaster").empty();
$.ajax({
type: 'POST',
url: '@Url.Action("GetPosts")', // Calling json method
dataType: 'json',
data: { id: $("#DistrictId").val() },
// Get Selected post id.
success: function (posts) {
$.each(posts, function (i, post) {
$("#PostMaster").append('<input type="checkbox" name="postdata">' + post.Text+'<br>');
});
},
error: function (ex) {
alert('Failed to retrieve post.' + ex);
}
});
return false;
})
});
</script>
 
 
When I hit on the create button by selecting the checkbox the selected checkbox is not listing in [HttpPost] of create parameter.How can I save the selected checkbox value as integer to db ? 
 why is that the value not showing in PostId. Can anyone please help me find a solution for this. How can I solve this ???

Answers (7)