简体   繁体   English

ASP.NET MVC 复选框始终为 false

[英]ASP.NET MVC checkbox always false

I made an asp.net website, but the checkbox is always false.我做了一个 asp.net 网站,但复选框总是错误​​的。 Why is this so?为什么会这样?

Model:型号:

 public string Username { get; set; }
 public string Password { get; set; }
 public bool Remember { get; set; }

CSHTML: CSHTML:

<div class="form-group">
    @Html.Label("Remember me?")
    @Html.CheckBoxFor(m => m.Remember)
 </div>

The Remember property is always false, if the checkbox is checked then Remember is still false. Remember属性始终为假,如果选中该复选框,则Remember仍然为假。

我遇到了同样的问题,我通过编写 html checkbox 标签来修复它,给它命名与属性名称相同的名称,并且 value = true,如果未选中复选框,则无需担心,因为无论如何它都不会提交,在您的情况就是这样

<input type="checkbox" name="Remember" value="true" />

With Razor, I had the same problem.使用 Razor,我遇到了同样的问题。 What worked for me was taking off the value="xxx" tag.对我有用的是去掉value="xxx"标签。 Then it functioned normally.然后就正常运行了。

Does not work:工作:

 <input class="form-check-input" value="true" asp-for="Answer.aIsCorrect" />

Works:作品:

 <input class="form-check-input" asp-for="Answer.aIsCorrect" />

The first parameter is not checkbox value but rather view model binding for the checkbox hence:第一个参数不是复选框值,而是复选框的视图模型绑定,因此:

@Html.CheckBoxFor(m => m.SomeBooleanProperty, new { @checked = "checked" }); @Html.CheckBoxFor(m => m.SomeBooleanProperty, new { @checked = "checked" }); The first parameter must identify a boolean property within your model (it's an Expression not an anonymous method returning a value) and second property defines any additional HTML element attributes.第一个参数必须标识模型中的布尔属性(它是一个表达式,而不是返回值的匿名方法),第二个属性定义任何其他 HTML 元素属性。 I'm not 100% sure that the above attribute will initially check your checkbox, but you can try.我不是 100% 确定上述属性最初会检查您的复选框,但您可以尝试。 But beware.但要小心。 Even though it may work you may have issues later on, when loading a valid model data and that particular property is set to false.即使它可能工作,您稍后可能会遇到问题,当加载有效的模型数据并且该特定属性设置为 false 时。

Source and additional info: https://stackoverflow.com/a/12674731/3397630来源和附加信息: https : //stackoverflow.com/a/12674731/3397630

Hope it will helpful for you ,kindly let me know your thoughts or feedbacks希望对您有所帮助,请让我知道您的想法或反馈

Thanks Karthik谢谢卡西克

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM