Search code examples
asp.net-mvc-4asp.net-mvc-viewmodel

How to capture multiple checkboxes and radio buttons posted data by viewmodel ASP.Net MVC


i am new in MVC. so this is my html looks like

<form id='your-form' action='@Url.Action("Action","Controller")' method='post'>
     <b>Gender</b><br />
     <input type='radio' name='gender' value='Male' /> Male <br />
     <input type='radio' name='gender' value='Female' /> Female <br />
     <hr />
     <b>Hobbies</b><br />
     <input type='checkbox' name='hobbies' value='Reading' /> Reading <br />
     <input type='checkbox' name='hobbies' value='Sports' /> Sports <br />
     <input type='checkbox' name='hobbies' value='Movies' /> Movies <br />
     <input type='submit' value='Update Profile' />
</form>

this way i am capturing data

public class HomeController : Controller
{  
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Index(string gender, string[] hobbies)
        {
            // Example output 
            var output = String.Format("The user's gender is <b>{0}</b> and they enjoy <b>{1}</b>", gender, String.Join(",", hobbies));
            return Content(output);
        }
}

but i like to know how could i capture it by viewmodel concept. anyone can help me with sample code. thanks


Solution

  • View models

    public class HobbyVM
    {
      public int ID { get; set; }
      public string Name { get; set; }
      public bool IsSelected { get; set; }
    }
    public class PersonVM
    {
      ....
      public string Gender { get; set; } // would be better to use an enum
      public List<HobbyVM> Hobbies { get; set; }
    }
    

    In the GET method, initialize an instance of the view model and pass it to the view

    public ActionResult Create()
    {
      PersonVM model = new PersonVM()
      {
        Hobbies = new List<HobbyVM>()
        {
          new HobbyVM(){ ID = 1, Name = "Reading" },
          new HobbyVM(){ ID = 2, Name = "Sports" },
          ....// etc these would actually be loaded from a repository
        }
      };
      return View(model);
    }
    [HttpPost]
    public ActionResult Create(PersonVM model)
    {
      // map you view model to a instance of your data model
      // save and redirect
    }
    

    View

    @model PersonVM
    @Html.BeginForm())
    {
      ....
      <label>
        @Html.RadioButtonFor(m => m.Gender, "Male", new { id = "" })
        <span>Male</span>
      </label>
      <label>
        @Html.RadioButtonFor(m => m.Gender, "Female", new { id = "" })
        <span>Female</span>
      </label>
      for(int i = 0; i < Model.Hobbies.Count; i++)
      {
        @Html.HidenFor(m => m.Hobbies[i].ID)
        @Html.CheckBoxFor(m => m.Hobbies[i].IsSelected)
        @Html.LabelFor(m => m.Hobbies[i].IsSelected, Model.Hobbies[i].Name)
      }
      <input type="submit" />
    }