[英]asp.net core razor page checkboxes model binding (always false)
i have a razor page in asp.net core with the following input tag:我在 asp.net 内核中有一个 razor 页面,带有以下输入标签:
<input asp-for="chkPref" />
in the code-behind i have:在代码隐藏中我有:
public bool chkPref { get; set; }
so when i run the app, i can confirm in Request.Form
that I'm getting...所以当我运行应用程序时,我可以在Request.Form
中确认我得到了......
checkbox checked = {true,false}
复选框选中 = {true,false}
checkbox unchecked = {false}
复选框未选中 = {false}
which is expected, according to https://www.learnrazorpages.com/razor-pages/forms/checkboxes (which seems to be the site everyone points to for answers to this issue)这是预期的,根据https://www.learnrazorpages.com/razor-pages/forms/checkboxes (这似乎是每个人都指向这个问题的答案的网站)
however, that page states that the model binding will figure out that {true,false}
is actually true
but i'm getting false
no matter what.但是,该页面指出 model 绑定会发现{true,false}
实际上是true
,但无论如何我都会变得false
。
the website above alludes to the fact that this "just happens"...上面的网站暗示了这种“刚刚发生”的事实......
If the checkbox is checked, the posted value will be true,false.如果选中该复选框,则发布的值将为真,假。 The model binder will correctly extract true from the value. model binder 将从值中正确提取 true。 Otherwise it will be false.否则会是假的。
but that doesn't seem to be working, or at least isn't that obvious how it works.但这似乎不起作用,或者至少它的工作原理并不那么明显。
i'm not exactly sure how you can assign two values (ie - true
, false
) to a single bool
in the first place.我不完全确定如何首先将两个值(即 - true
, false
)分配给单个bool
。
i even tried turning it into a List<bool>
but that didn't work either.我什至尝试将它变成List<bool>
但这也不起作用。 that throws a whole different set of errors.这会引发一组完全不同的错误。
I believe looking at the Request.Form
gives you the raw form data.我相信查看Request.Form
可以为您提供原始表单数据。 What you probably want is to leverage form binder:您可能想要的是利用表单活页夹:
you can either mark propertes with BindPropertyAttribute
or indicate you expect these specific properties as parameters to your OnPost
handler (see example below).您可以使用BindPropertyAttribute
标记属性,或者指示您希望这些特定属性作为OnPost
处理程序的参数(参见下面的示例)。
Given a razor page给定一个 razor 页面
<form method="post">
<input asp-for="chkPref" />
@Html.CheckBoxFor(model => model.chkPref2)
<button>Click</button>
</form>
your code-behind could look like so:您的代码隐藏可能如下所示:
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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.