C# 如何反序列化复选框值的JSON数据?
我在一个表单中有多个复选框值。我正在序列化表单并将其作为JSON数据发送给mvc控制器。如何反序列化复选框值 这是我的html-C# 如何反序列化复选框值的JSON数据?,c#,javascript,jquery,asp.net-mvc,json,C#,Javascript,Jquery,Asp.net Mvc,Json,我在一个表单中有多个复选框值。我正在序列化表单并将其作为JSON数据发送给mvc控制器。如何反序列化复选框值 这是我的html- @using (Html.BeginForm("SaveOfficeConfiguration", "Offices", FormMethod.Post, new { Id = "frmOfficeConfigSave" })) { <div id="divOfficeForm"> <div style="width: auto; hei
@using (Html.BeginForm("SaveOfficeConfiguration", "Offices", FormMethod.Post, new { Id = "frmOfficeConfigSave" }))
{
<div id="divOfficeForm">
<div style="width: auto; height: auto; border: 3px outset silver;">
<table class="mainsectionable" width="100%">
<thead>
<tr>
<th style="text-align: center;">
<center>KCCM Profile Access</center>
</th>
</tr>
<tr>
<td>
@using (Html.BeginForm())
{
IEnumerable<SelectListItem> Brands = ViewBag.GetBrands;
foreach (var item in Brands)
{
@Html.CheckBox("KCCM_Brands", false, new
{
value = item.Value
});
<label>@item.Text</label><br />
}
}
</td>
</tr>
</thead>
</table>
</div>
</div>
}
这是我的行动-
[HttpPost]
public ActionResult SaveOfficeConfiguration(int ? officeID, FormCollection form)
{
try
{
*/..............
..............*/
return Json(new
{
success = true,
msg = String.Empty,
id = 1
}, JsonRequestBehavior.AllowGet);
}
catch (Exception error)
{
return Json(new
{
success = false,
msg = error.Message,
id = -1
}, JsonRequestBehavior.AllowGet);
}
}
您只需接收一个
列表
参数,该参数与您在复选框中给出的名称相同,即KCM_品牌
。模型绑定器将直接为您反序列化它
[HttpPost]
public ActionResult SaveOfficeConfiguration(int ? officeID, FormCollection form,
List<string> KCM_Brands)
{
....
}
[HttpPost]
public ActionResult SaveOfficeConfiguration(int?officeID、FormCollection表单、,
列出KCM_品牌)
{
....
}
若要序列化表单数据以进行发布,请使用本文中建议的函数:
您可以使用
表单集合
检索复选框值:
控制器:
[HttpPost]
public ActionResult SaveOfficeConfiguration(int ? officeID, FormCollection form)
{
var CheckBoxValues = form["KCCM_Brands"].Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(x=>int.Parse(x));
}
有关更多信息,请查看此处:
而不是
@Html.CheckBox("KCCM_Brands", false, new
{
value = item.Value
});
使用此代码生成复选框
<input type="checkbox" name="KCCM_Brands" value="@item.Value" />
我有3个复选框,我先选中,最后选中,然后提交表格。当我使用您的代码时,我得到的值为
“1”、“false”、“false”、“3”、“false”
您必须从列表中删除这些false。您的结果为您提供了所选的复选框。我如何从这些值中知道所选的复选框?我在这里感到困惑,我在这里找不到任何值。@sandy访问回答中的链接。我必须遵循Json序列化列出KCCM_品牌
isnull
!它的null
,我的javascript函数有问题吗?我没有检查你的js。是的,这是错误的。我以为你已经检查了警报发送的内容。看看我添加的参考资料
<input type="checkbox" name="KCCM_Brands" value="@item.Value" />
public ActionResult SaveOfficeConfiguration(int? officeID, List<string> KCCM_Brands)
data: $('#frmOfficeConfigSave input').serialize()