C#ASP.NET:复选框和单选按钮存在问题 [英] C# ASP.NET : Issue with check box and radio button

查看:169
本文介绍了C#ASP.NET:复选框和单选按钮存在问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个应用程序,用户可以在其中填写并非必须设置某些属性的表单.这包括复选框和单选按钮.

I am creating an app where the users fill a form where the setting of some properties are not mandatory. This includes check boxes and radio buttons.

所以,我的模型中有这样的东西:

So, I have something like this in my model:

public class MyModel {
     public bool boolvalue;
     public MyTwoValuedType mytypevalue;
}

我认为:

@model MyModel

<form method="post">
   @Html.CheckBoxFor(m => m.boolvalue)

   @Html.RadioButtonFor(m => m.mytypevalue, mytypevalue.Value1)

   @Html.RadioButtonFor(m => m.mytypevalue, mytypevalue.Value2)
</form>

初始化视图时,我通过控制器中的return View();发送一个空模型,并且单选按钮没有值(未选中单选按钮)并且未选中复选框(因此其值为false). 但是,我想使用像(bool?MyTwoValuedType?)这样的可为空的类型,一旦我想要,如果提交表单(在视图中)而没有用户更改了复选框的值,和单选按钮,它们没有默认值.即使表单提交有错误,表单的重新出现(由于验证失败)在复选框和单选按钮中也具有用户未设置的值...

When I initialize the view I send an empty model through return View(); in the controller, and the radio buttons have no value (no radio button checked) and the check box is not checked (so its value is false). However, I would like to use nullable types, like (bool? and MyTwoValuedType?), once that I want that if the submission of the form (in the View) is made without the user have changed the value of the check boxes and radio buttons, they don't get a default value. Even when the submission of the form has an error, the reappearance of the form (because fails validation) has values in the check boxes and radio buttons that were not set by the user…

我应该将Html.DropDownListFor与可为null的类型一起使用,而不是使用复选框和单选按钮吗?这样会产生好结果吗?

Should I use Html.DropDownListFor with nullable types instead of check boxes and radio buttons? Would this have a good result?

推荐答案

将@ Html.DropDownListFor用于可为空的属性,因为当您在视图中发送空模型然后在POST中发送时,您会得到false作为布尔值返回. 您不能将复选框用于布尔模型.

Use @Html.DropDownListFor for nullable properties because when you send empty model in view and then in POST you will get false as boolean return. You cannot use checkbox for boolean model.

如果要使用复选框和单选框表示布尔值,请使用jquery设置值. 但是DropdownList最适合布尔模型属性.

And if you want to use checkbox and radio for boolean then use jquery to set value. but DropdownList is Best for boolean model property.

这篇关于C#ASP.NET:复选框和单选按钮存在问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆