Reputation: 2155
What is the most elegant way to define a group of radiobuttons in MVC5+ view?
Suppose I have a view model like so
public class ViewModel
{
public bool Value1 {get;set;}
public bool Value2 {get;set;}
}
And I want to render this on an MVC5+ view so its either Value1 or Value2? In WebForms I would put them on one line and define a common GroupName property for them, while in plain HTML I would make a pair of input type=radio and give them a common "name" attribute. What is the best way to do this in MVC using attributes/data annotations?
Thanks
Upvotes: 3
Views: 2716
Reputation: 1
Just want to add something here
Please add [BindProperty]
attribute to the property Gender
incase you are using
<input type = radio" name = "ViewModel.Gender" value="Male">
<input type = radio" name = "ViewModel.Gender" value="Female">
Like this in your cshtml
to make it work and populate the input model with the value selected for Gender
Upvotes: 0
Reputation: 11
Its better to have a class for example "Employee" referenced in the viewmodel class. Then you assign the viewmodel to the view, where you can reference any class within the viewmodel.
The below example would give you two radio buttons which will give you male or female for the "Gender" attribute of your question. So if your question was "What is your gender?" The user then selects Male or Female. Then in the controller you could ask which value the user selected.
Your ViewModel class would be this:
public class ViewModel
{
public Employee Employee {get;set;}
}
Your Employee class would be this:
public class Employee
{
public string Gender {get; set;}
}
Your Controller would be this:
using GenderApplication.Models;
public ActionResult Create()
{
return View();
}
[HttpPost]
public ActionResult Create(ViewModel viewModel)
{
//whatever you wanted to do with viewModel.Employee.Gender
return RedirectToAction("Index");
}
Your view would then be:
@model GenderApplication.Models.ViewModel
@using (Html.BeginForm())
{
@Html.RadioButtonFor(model => model.Employee.Gender, "Male")
<text>True</text>
<br />
@Html.RadioButtonFor(model => model..Employee.Gender, "Female")
<text>False</text>
<br />
<input type="submit" value="Submit" formaction="@Url.Action("Create")" />
Upvotes: 1