asp.net 核心剃须刀页面复选框模型绑定(始终为 false)
asp.net core razor page checkboxes model binding (always false)
我在 asp.net 核心中有一个 razor 页面,具有以下输入标签:
<input asp-for="chkPref" />
在代码隐藏中我有:
public bool chkPref { get; set; }
所以当我 运行 应用程序时,我可以在 Request.Form
中确认我正在...
复选框已选中 = {true,false}
复选框未选中 = {false}
这是预期的,根据 https://www.learnrazorpages.com/razor-pages/forms/checkboxes(这似乎是每个人都指向该问题的答案的网站)
然而,该页面声明模型绑定将计算出 {true,false}
实际上是 true
,但无论如何我都会得到 false
。
上面的网站暗示了这个 "just happens"...
If the checkbox is checked, the posted value will be true,false. The
model binder will correctly extract true from the value. Otherwise it
will be false.
但这似乎并没有奏效,或者至少不是那么明显。
我不太确定如何首先将两个值(即 - true
、false
)分配给单个 bool
。
我什至尝试将它变成 List<bool>
,但这也没有用。抛出一组完全不同的错误。
我相信查看 Request.Form
可以为您提供原始表单数据。您可能想要的是利用表单活页夹:
您可以使用 BindPropertyAttribute
标记属性,或者表明您希望这些特定属性作为您的 OnPost
处理程序的参数(参见下面的示例)。
给定一个剃刀页面
<form method="post">
<input asp-for="chkPref" />
@Html.CheckBoxFor(model => model.chkPref2)
<button>Click</button>
</form>
您的代码隐藏可能如下所示:
public class IndexModel : PageModel
{
public bool chkPref { get; set; } // will not get bound
[BindProperty] // Binder needs to know which properties to work with
public bool chkPref2 { get; set; }
public void OnPost(bool chkPref)// PageActionInvoker will pass correct value as parameter
{
this.chkPref = chkPref;
}
}
我在 asp.net 核心中有一个 razor 页面,具有以下输入标签:
<input asp-for="chkPref" />
在代码隐藏中我有:
public bool chkPref { get; set; }
所以当我 运行 应用程序时,我可以在 Request.Form
中确认我正在...
复选框已选中 = {true,false}
复选框未选中 = {false}
这是预期的,根据 https://www.learnrazorpages.com/razor-pages/forms/checkboxes(这似乎是每个人都指向该问题的答案的网站)
然而,该页面声明模型绑定将计算出 {true,false}
实际上是 true
,但无论如何我都会得到 false
。
上面的网站暗示了这个 "just happens"...
If the checkbox is checked, the posted value will be true,false. The model binder will correctly extract true from the value. Otherwise it will be false.
但这似乎并没有奏效,或者至少不是那么明显。
我不太确定如何首先将两个值(即 - true
、false
)分配给单个 bool
。
我什至尝试将它变成 List<bool>
,但这也没有用。抛出一组完全不同的错误。
我相信查看 Request.Form
可以为您提供原始表单数据。您可能想要的是利用表单活页夹:
您可以使用 BindPropertyAttribute
标记属性,或者表明您希望这些特定属性作为您的 OnPost
处理程序的参数(参见下面的示例)。
给定一个剃刀页面
<form method="post">
<input asp-for="chkPref" />
@Html.CheckBoxFor(model => model.chkPref2)
<button>Click</button>
</form>
您的代码隐藏可能如下所示:
public class IndexModel : PageModel
{
public bool chkPref { get; set; } // will not get bound
[BindProperty] // Binder needs to know which properties to work with
public bool chkPref2 { get; set; }
public void OnPost(bool chkPref)// PageActionInvoker will pass correct value as parameter
{
this.chkPref = chkPref;
}
}