Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I bind a radio button with model data in ASP.Net MVC?

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.

like image 797
Thomas Avatar asked Sep 17 '13 14:09

Thomas


2 Answers

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);
}
like image 74
mgalindez Avatar answered Sep 20 '22 22:09

mgalindez


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.

like image 37
Mahaveer Jangid Avatar answered Sep 18 '22 22:09

Mahaveer Jangid