Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Jquery 如何将多个选中复选框值保存到数据库mvc_Jquery_Sql Server_Asp.net Mvc_Asp.net Mvc 4_Checkbox - Fatal编程技术网

Jquery 如何将多个选中复选框值保存到数据库mvc

Jquery 如何将多个选中复选框值保存到数据库mvc,jquery,sql-server,asp.net-mvc,asp.net-mvc-4,checkbox,Jquery,Sql Server,Asp.net Mvc,Asp.net Mvc 4,Checkbox,我正在开发一个MVC项目,我的任务是在复选框中选择多个项目,并希望将这些选定的项目保存到数据库中。为此,我创建了三个表。第一个是DistrictMaster public partial class DistrictMaster { public int Id { get; set; } public string DistrictName { get; set; } public virtual ICollection<PostMaster> PostMas

我正在开发一个MVC项目,我的任务是在复选框中选择多个项目,并希望将这些选定的项目保存到数据库中。为此,我创建了三个表。第一个是DistrictMaster

public partial class DistrictMaster
{
    public int Id { get; set; }
    public string DistrictName { get; set; }
    public virtual ICollection<PostMaster> PostMasters { get; set; }
}
公共部分类DistrictMaster
{
公共int Id{get;set;}
公共字符串DistrictName{get;set;}
公共虚拟ICollection邮局管理员{get;set;}
}
在这里,我输入了各个地区,并保存到数据库中 二等邮政署长

 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; }
}
公共部分类邮政局长
{
公共int Id{get;set;}
公共字符串PostName{get;set;}
公共字符串PIN{get;set;}
公共可为空的DistrictID{get;set;}
公共虚拟DistrictMaster DistrictMaster{get;set;}
}
在这里,我根据从下拉列表中选择的地区输入不同的帖子。DistrictID是外键,将pincode和名称保存到表中相应的地区

第三个表是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; }
}
public分部类AgentPostMapping
{
公共int Id{get;set;}
公共可为空的AgentId{get;set;}
公共可为空的PostId{get;set;}
公共可为空的生效日期{get;set;}
}
这里的PostId不是外键,我需要将选中或选中的项目保存为该PostId的整数。这是我做起来很麻烦的部分

控制器

 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);
    }
public ActionResult Create()
{
ViewBag.AgentId=新的选择列表(db.AgentMasters,“ID”,“FirstName”);
ViewBag.DistrictId=新的选择列表(db.DistrictMasters,“Id”,“DistrictName”);
返回视图();
}
公共JsonResult GetPosts(字符串id)
{
列表帖子=新列表();
var postList=this.Getpost(Convert.ToInt32(id));
ViewBag.Postdata=this.Getpost(Convert.ToInt32(id));
var postData=postList.Select(m=>newselectListItem()
{
Text=m.PostName,
Value=m.Id.ToString(),
});
返回Json(postData,JsonRequestBehavior.AllowGet);
}
公共IList Getpost(int DistrictId)
{
返回db.PostMasters.Where(m=>m.DistrictID==DistrictID.ToList();
}
[HttpPost]
[ValidateAntiForgeryToken]
公共异步任务

当我通过选中复选框点击create按钮时,选中的复选框未在create参数的[HttpPost]中列出

它是这样显示的


为什么PostId中没有显示该值。谁能帮我找到解决办法。如何解决这个问题?

我认为您应该创建一个名为“
PostId
”的
input

我看到一个
@Html.LabelFor
和一个
@Html.ValidationMessageFor
,但是
编辑器在哪里


你不需要使用HTML助手,在某个地方需要一个名为“
PostId
”的
input
(复选框)

我认为你应该创建一个名为“
PostId
”的
input

我看到一个
@Html.LabelFor
和一个
@Html.ValidationMessageFor
,但是
编辑器在哪里


您不需要使用HTML助手,在某个地方需要一个名为“
PostId
”的
输入(复选框)

一切似乎都正常 问题的解决方案是,您可以使用name属性获取元素的值。 将jquery中试图追加的名称属性name=“postdata”更改为name=“postd”


或者您可以将modelposted中的属性名称更改为postdta

一切似乎都正常 问题的解决方案是,您可以使用name属性获取元素的值。 将jquery中试图追加的名称属性name=“postdata”更改为name=“postd”


或者,您可以将modelPostId中的属性名称更改为postdta

复选框的模型应该是字符串数组。每个选中的复选框都与数组中的一个字符串元素(其ID)相对应。如果您创建一个只包含复选框的简单演示,那么这个问题可能更容易回答。请同时在你的问题中显示视图。我的问题中包含了视图页面。我觉得这很复杂,但可能我错过了你想做的事情。看看这个解决方案:不,我没有得到那个解决方案。但为什么所选项目没有显示在控制器中创建的post方法中?复选框的模型应该是字符串数组。每个选中的复选框都与数组中的一个字符串元素(其ID)相对应。如果您创建一个只包含复选框的简单演示,那么这个问题可能更容易回答。请同时在你的问题中显示视图。我的问题中包含了视图页面。我觉得这很复杂,但可能我错过了你想做的事情。看看这个解决方案:不,我没有得到那个解决方案。但是,为什么在控制器中创建的post方法中未显示所选项目?Iam在jquey中获取所选复选框项目,但如何将此值传递给控制器以将这些所选项目保存到数据库Iam在jquey中获取所选复选框项目,但如何将此值传递给控制器以保存这些所选项目到数据库
@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;
})
});