Click here to Skip to main content
15,890,882 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more: , +
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 () {
    //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" 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);// assign to hidden field
   });
</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
Posted
Updated 14-Apr-17 2:38am
Comments
Karthik_Mahalingam 11-Apr-17 1:56am    
post the action method for GetPosts
ammu11 11-Apr-17 2:23am    
GetPost is used to give to jquery part which I have shown in my question
Karthik_Mahalingam 11-Apr-17 3:10am    
c# method
ammu11 11-Apr-17 3:24am    
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();
}
Karthik_Mahalingam 11-Apr-17 3:29am    
it should be
                    $("#PostMaster").append('<input type="checkbox" name="postdata" value=' + post.Value + '>' + post.Text + '<br>');                    

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900