我的表单中有一个复选框字段。当编辑并重新提交表单时,始终传递给控制器的复选框的值为false。我正在使用ASP.Net MVC Core 2.2。
Edit.cshtml
<form asp-action="Edit">
<table>
<tr>
<td><label for="default">Default</label></td>
<td>@Html.CheckBoxFor(m => m.IsDefault, new { @checked = "checked", @class = "form-input-styled" })</td>
</tr>
<tr>
<td><label for="standard">Standard</label></td>
<td>@Html.CheckBoxFor(m => m.IsStandard, new { @checked = "checked", @class = "form-input-styled" })</td>
</tr>
<tr>
<td><label for="emailed">Emailed</label></td>
<td>@Html.CheckBoxFor(m => m.IsEmailed, new { @checked = "checked", @class = "form-input-styled" })</td>
</tr>
</table>
</form>
ViewModel.cs
public class ReprintEditViewModel
{
public bool IsDefault { get; set; }
public bool IsStandard { get; set; }
public bool IsEmailed { get; set; }
}
Controller.cs
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, [Bind("Id,Date,PolicyNumber,OwnerName,SendTo,EmailAddress,ModifiedDate,LastModifiedBy,DeliveryMethod, Default, Standard, Emailed")] ReprintEditViewModel xrCertReprint)
{
if (ModelState.IsValid)
{
//string dm = string.Join(", ", DeliveryMethod);
string dm = "";
if (xrCertReprint.IsDefault == true)
dm = "Default";
if (xrCertReprint.IsStandard == true)
if (dm.Length > 1)
dm = dm + ", " + "Standard";
else
dm = "Standard";
if (xrCertReprint.IsEmailed == true)
if (dm.Length > 1)
dm = dm + ", " + "Emailed";
else
dm = "Emailed";
return RedirectToAction(nameof(Index));
}
return View(xrCertReprint);
}
我尝试了stackoverflow中列出的其他解决方案/方式。什么都没解决。我不确定自己做错了什么?
答案 0 :(得分:1)
当前,您正在使用以下代码绑定数据:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, [Bind("Id,Date,PolicyNumber,OwnerName,SendTo,EmailAddress,ModifiedDate,LastModifiedBy,DeliveryMethod, Default, Standard, Emailed")] ReprintEditViewModel xrCertReprint)
{
if (ModelState.IsValid)
{
//string dm = string.Join(", ", DeliveryMethod);
string dm = "";
if (xrCertReprint.IsDefault == true)
dm = "Default";
if (xrCertReprint.IsStandard == true)
if (dm.Length > 1)
dm = dm + ", " + "Standard";
else
dm = "Standard";
if (xrCertReprint.IsEmailed == true)
if (dm.Length > 1)
dm = dm + ", " + "Emailed";
else
dm = "Emailed";
return RedirectToAction(nameof(Index));
}
return View(xrCertReprint);
}
虽然模型ReprintEditViewModel
具有属性IsDefault , IsStandard and IsEmailed
,但属性未包含在Bind属性中。因此,MVC模型绑定程序将忽略这些属性,而仅绑定传入属性的属性。如果删除Bind属性,则由于MVC默认模型绑定程序的缘故,所有与Model中具有相同名称的属性都将绑定,并且您将获得值。
您可以使用this link
了解有关模型绑定的更多信息答案 1 :(得分:1)
原因是您的[Bind]
属性未包含正确的属性名称。
[Bind]
属性指定模型绑定中应包括模型的哪些属性。
更改为使用IsDefault, IsStandard, IsEmailed
代替Default, Standard, Emailed
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, [Bind("Id,Date,PolicyNumber,OwnerName,SendTo,EmailAddress,ModifiedDate,LastModifiedBy,DeliveryMethod, IsDefault, IsStandard, IsEmailed")] ReprintEditViewModel xrCertReprint)