16

I want to show a radio button in my form which will be populated from model data.

here is my model

public class Student
    {
        [Required(ErrorMessage = "First Name Required")] // textboxes will show
        [Display(Name = "First Name :")]
        [StringLength(5, ErrorMessage = "First Name cannot be longer than 5 characters.")]
        public string FirstName { get; set; }

[Required(ErrorMessage = "Last Name Required")] // textboxes will show
        [Display(Name = "Last Name :")]
        [StringLength(5, ErrorMessage = "Last Name cannot be longer than 5 characters.")]
        public string LastName { get; set; }

[Required(ErrorMessage = "Sex Required")] // group of radio button will show
        [Display(Name = "Sex :")]
        public List<Sex> Sex { get; set; }

}

public class Sex
    {
        public string ID { get; set; }
        public string Type { get; set; }
    }

here I am trying to populate the student model manually from an action method like

public ActionResult Index()
{
var student=  new Student 
{
    FirstName = "Rion",
    LastName = "Gomes",

    Sex= new List<Sex>
        {
            new Sex{ID="1" , Type = "Male"}, 
            new Sex{ID="2" , Type = "Female"}
        }    
}    
    return View(student);
}

now how could I generate a radio button which will display text in form Male & Female and as value will have the ID

I searched google and found many samples and I used one but not sure if it works. here is the radio button code in view.

@Html.RadioButtonFor(x => x.Sex, "Male")

I do not want to hard code male or female rather; I want to show it through a model and want to generate the radio button in a for loop.

I am new too MVC, so please guide me.

A_Arnold
  • 3,195
  • 25
  • 39
Thomas
  • 33,544
  • 126
  • 357
  • 626
  • Great answer here: http://stackoverflow.com/questions/6638966/mvc-radiobutton-binding-complex-object Notice the foreach() loop at the bottom. – MondayPaper Sep 17 '13 at 14:47

2 Answers2

36

If I understood correctly you should change your Student model in order to have the property "Sex" as an integer and then you should have another property called "SexList" where you populate the list. This change will allow you to post your data and retrieve the sex selected by the user.

If you are using Razor view engine you should do something like this:

@{ 
    foreach (var sex in Model.SexList)
    {
        <div>
            @Html.RadioButtonFor(model => model.Sex, new { id = "sex" + sex.ID })
            @Html.Label("sex" + sex.ID, sex.Type)
        </div>
    }
}

Edit:

Your model should be something like this:

public class Student
{
    [Required(ErrorMessage = "First Name Required")] // textboxes will show
    [Display(Name = "First Name :")]
    [StringLength(5, ErrorMessage = "First Name cannot be longer than 5 characters.")]
    public string FirstName { get; set; }

    [Required(ErrorMessage = "Last Name Required")] // textboxes will show
    [Display(Name = "Last Name :")]
    [StringLength(5, ErrorMessage = "Last Name cannot be longer than 5 characters.")]
    public string LastName { get; set; }

    [Required(ErrorMessage = "Sex Required")]
    [Display(Name = "Sex :")]
    public Sex Gender { get; set; }

    public List<Sex> SexList { get; set; }

}

public class Sex
{
    public string ID {get;set;}
    public string Type {get;set;}
}

Your action in the controller:

[HttpGet]
public ActionResult Index()
{
    var student = new Student 
    {
        FirstName = "Rion",
        LastName = "Gomes",

        //I think the best way to populate this list is to call a service here.
        SexList = new List<Sex>
        {
            new Sex{ID="1" , Type = "Male"}, 
            new Sex{ID="2" , Type = "Female"}
        }    
    }    

    return View(student);
}

And the View:

@Html.BeginForm()
{
    <div>
        @Html.LabelFor(model => model.FirstName)
        @Html.EditorFor(model => model.FirstName)
        @Html.ValidationMessageFor(model => model.FirstName)
    </div>
    <div>
        @Html.LabelFor(model => model.LastName)
        @Html.EditorFor(model => model.LastName)
        @Html.ValidationMessageFor(model => model.LastName)
    </div>
    @{ 
        foreach (var sex in Model.SexList)
        {
            <div>
                @Html.RadioButtonFor(model => model.Gender, new { id = "sex" + sex.ID })
                @Html.Label("sex" + sex.ID, sex.Type)
            </div>
        }
    }

    <input type="submit" value"Submit" />
}

and you should have an action in your controller this way. This is the place where the submit is going to post the data:

[HttpPost]
public ActionResult Index(Student model)
{
    if (ModelState.IsValid)
    {
        //TODO: Save your model and redirect 
    }

    //Call the same service to initialize your model again (cause we didn't post the list of sexes)
    return View(model);
}
A_Arnold
  • 3,195
  • 25
  • 39
mgalindez
  • 611
  • 6
  • 10
  • can u plzz discuss it with a complete sample code like sex & student model and populate these model manually and generate UI and capture the post data from where we can extract what user selected. – Thomas Sep 18 '13 at 07:50
  • In your example, you make a List, do you just then assume there is an object like that? Also you declare two variables named "Sex", both the list and the int. Does this code run? – melwil Feb 15 '16 at 12:13
  • 1
    @melwil The second property was called SexList, you were right, there was a duplication there. Regarding to the Sex class is the same that you can find on the question. – mgalindez Feb 16 '16 at 20:55
1

First, create Enum

public enum QuestionDetails
    {

        Description = 1,            
        Attachment = 2,           
        DescriptionandAttachment = 3        
    }

Second Model Part

    public class QuestionModel
      {
        public QuestionDetails answerFiledType { get; set; }

        public string answerFiledTypeValue
        {
            get { return answerFiledType.ToString(); }
            set { answerFiledType = ((QuestionDetails)Enum.Parse(typeof(QuestionDetails), value.ToUpper().ToString())); }
        }
}

Razor:

 <label class="custom-control custom-radio">
                @Html.RadioButtonFor(m => m.answerFiledType, WM_GlobalLib.EnumHelper.QuestionDetails.Description, new { @name = "radio", @type = "radio",@id = "Description" })
                <span class="custom-control-indicator"></span>
                <span class="custom-control-description">Description</span>
            </label>
            <label class="custom-control custom-radio">
                @Html.RadioButtonFor(m => m.answerFiledType, WM_GlobalLib.EnumHelper.QuestionDetails.Attachment, new { @name = "radio", @type = "radio", @id = "Attachment" })
                <span class="custom-control-indicator"></span>
                <span class="custom-control-description">Attachment</span>
            </label>
            <label class="custom-control custom-radio">
                @Html.RadioButtonFor(m => m.answerFiledType, WM_GlobalLib.EnumHelper.QuestionDetails.DescriptionandAttachment, new { @name = "radio", @type = "radio",@id = "DescriptionandAttachment" })
                <span class="custom-control-indicator"></span>
                <span class="custom-control-description">DescriptionandAttachment</span>
            </label>

Controller Part:

Now you can get value of selected value through Model Propery and can save in database and also can edit.

Kaushik Thanki
  • 3,334
  • 3
  • 23
  • 50
Mahaveer Jangid
  • 366
  • 2
  • 11