如何通过viewmodel ASP.Net MVC捕获多个复选框和单选按钮发布的数据

时间:2015-08-27 11:37:58

标签: asp.net-mvc-4 asp.net-mvc-viewmodel

我是MVC的新手。所以这是我的html看起来像

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

这样我捕获数据

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);
        }
}

但我想知道如何通过viewmodel concept捕获它。任何人都可以帮我提供示例代码。感谢

1 个答案:

答案 0 :(得分:1)

查看模型

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; }
}

在GET方法中,初始化视图模型的实例并将其传递给视图

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
}

查看

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