ASP.NET MVC 中将FormCollection与实体间转换方法【转】

将Action动作中传递的FormCollection转变成对应的实体,可以使用Controller的TryUpdateModel()方法。

示例如下:

[csharp]view plaincopyprint?

  1. [HttpPost]
  2. public ActionResult Create(FormCollection collection)
  3. {
  4. try
  5. {
  6. if (ModelState.IsValid)
  7. {
  8. var student = new Student();
  9. //在这里转换
  10. TryUpdateModel<Student>(student, collection);
  11. dalStudent.Add(student);
  12. return RedirectToAction("Index");
  13. }
  14. else
  15. return View();
  16. }
  17. catch
  18. {
  19. return View("Create");
  20. }
  21. }