Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.Net MVC3 ViewModel with Radio Button not working

Here is my ViewModel class which i am binding with a radio button and check box

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

Issue: For check box in a controller class i can able to see IsSelected property with the binded model is true if select. But in case of Radio button it always shows false. Any help appreciated

Check Box

Razor code

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

Produced HTML

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

Radio Button

Razor:

 @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">

What could be the problem here?

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.
like image 308
Murali Murugesan Avatar asked Dec 19 '12 14:12

Murali Murugesan


1 Answers

The value property of the radio button is what gets sent to the server, so in this case, the value 6 is being sent but the server can't stick 6 into Isselected b/c Isselected is of type boolean.

You need to change the html to this

@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.

like image 142
Omar Avatar answered Nov 02 '22 12:11

Omar