SQL Server how to save multiple selected checkbox value to database mvc

hgc7kmma  于 12个月前  发布在  其他
关注(0)|答案(2)|浏览(125)

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)

@model BeyondThemes.BeyondAdmin.Models.AgentPostMapping

@using (Html.BeginForm()) 
{
@Html.AntiForgeryToken()

<div class="form-horizontal">
 @Html.ValidationSummary(true, "", new { @class = "text-danger" })
  <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" })
            @*@Html.DropDownList("DistrictID", null, "select", htmlAttributes: new { @class = "form-control" })*@
            @*@Html.ValidationMessageFor(model => model.PostMaster.DistrictID, "", new { @class = "text-danger" })*@
        </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('<option value="' + post.Value + '">' +
                //    post.Text + '</option>');

                $("#PostMaster").append('<input type="checkbox" name="postdata">' + post.Text+'<br>');
            });
        },
        error: function (ex) {
            alert('Failed to retrieve post.' + ex);
        }
    });
    return false;
})
});

This is the screen shot of how the page to look like

When I hit on the create button by selecting the checkbox the selected checkbox is not listing in [HttpPost] of create parameter

it shows like this

why is that the value not showing in PostId. Can anyone please help me find a solution for this. How can I solve this ???

kdfy810k

kdfy810k1#

Every thing seem to be alright solution of your problem is that you can get value of element using name attribute. either change name attribute name="postdata" to name="PostId" in jquery where you are trying to append checkbox.

or you can change property name in model PostId to postdta

ozxc1zmp

ozxc1zmp2#

I think you should create an input with the name ' PostId '.

I see a @Html.LabelFor and a @Html.ValidationMessageFor , but where is the EditorFor ?

You don't need to use a HTML-Helper, somewhere needs to be an input (checkbox) with the name ' PostId '

相关问题