10

这是我用单选按钮和复选框绑定的 ViewModel 类

public class MyListViewModel
{
    public bool Isselected { get; set; }
    public Int32 ID { get; set; }      
    public string EmpName { get; set; }
    
}

问题: 对于控制器类中的复选框,如果选择,我可以看到绑定模型的 IsSelected 属性为真。但在单选按钮的情况下,它总是显示为假。任何帮助表示赞赏

复选框

剃刀代码

 @Html.CheckBox(myListObj.Isselected.ToString(), myListObj.Isselected, 
  new { id = myListObj.Isselected.ToString() })

生成的 HTML

 <input type="checkbox" value="true" name="myListObj[0].Isselected" id="22">
 <input type="hidden" value="false" name="myListObj[0].Isselected">

单选按钮

剃刀:

 @Html.RadioButton(myListObj.Isselected.ToString(), myListObj.ID, 
 myListObj.Isselected, new { id = myListObj.Isselected.ToString() }) 

html:

<input type="radio" value="6"
 name="myListObj[0].Isselected" id="myListObj[0].Isselected">

这里可能是什么问题?

Edited: 
What could be the code for binding a model with multiselect radio button. 
I mean user can select more than one Employee from a list. 
I want to know what are the employees selected with the help of Model Binding 
class with the property IsSelected. Please suggest me the possible way.
4

1 回答 1

1

单选按钮的value属性是发送到服务器的内容,因此在这种情况下,6正在发送值,但服务器无法6插入Isselectedb/cIsselected类型boolean

您需要将 html 更改为此

@Html.RadioButton(myListObj.Isselected.ToString(), true, myListObj.Isselected, new { id = myListObj.Isselected.ToString() })

Note how I changed myListObj.ID to just true. This says to the browser "if the user selects this radio button, send the value true to the server".

Alternatively, you could change Isselected to a double? and continue using the ID value. This way, if the radio button is not selected, the server will see null; if it is selected, the server will see 6.

于 2012-12-19T19:34:07.157 回答