我是 MVC3 的新手,我想知道这是否可能和好的做法?
我有一个工作正常的模型+视图+控制器。此视图显示人员列表 - 我希望能够单击一个人的姓名并被重定向到一个新视图,该视图将显示该人员的详细信息。这个新视图只有一个 ViewModel,但没有控制器,因为我打算在操作中传入对象。
Person 对象包含我的视图需要显示的所有属性:@Html.ActionLink(item.Person.FirstName, "PersonDetails", item.Person)
这是可能的/好的做法吗?
我是 MVC3 的新手,我想知道这是否可能和好的做法?
我有一个工作正常的模型+视图+控制器。此视图显示人员列表 - 我希望能够单击一个人的姓名并被重定向到一个新视图,该视图将显示该人员的详细信息。这个新视图只有一个 ViewModel,但没有控制器,因为我打算在操作中传入对象。
Person 对象包含我的视图需要显示的所有属性:@Html.ActionLink(item.Person.FirstName, "PersonDetails", item.Person)
这是可能的/好的做法吗?
我相信您对 MVC 的工作方式有误解。您的 ActionLink 将始终重定向到控制器的相应 ActionMethod。您要做的是在您的控制器中创建一个操作方法,该方法接受必要的参数,然后返回您的 ViewModel 视图。
这是一个非常快速的示例,可以帮助您入门:
public class HomeController : Controller
{
public ActionResult List()
{
return View();
}
public ActionResult DetailById(int i)
{
// load person from data source by id = i
// build PersonDetailViewModel from data returned
return View("PersonDetails", PersonDetailViewModel);
}
public ActionResult DetailByVals(string FirstName, Person person)
{
// build PersonDetailViewModel manually from data passed in
// you may have to work through some binding issues here with Person
return View("PersonDetails", PersonDetailViewModel);
}
}
不是一个像你想要的那样做的好方法(在你原来的帖子中)。视图应始终具有视图模型。视图模型仅代表您希望在视图上拥有的数据,不多也不少。不要将您的 domail 模型传递给视图,而是使用视图模型。这个视图模型可能只包含你的域模型的一部分属性。
在您的列表视图中,您可能有一个网格,并且在每一行旁边您可能有一个详细信息链接,或者名称上的链接(如您所拥有的那样)。单击其中任何一个链接时,您将被定向到详细信息视图。此详细信息视图将拥有自己的视图模型,其中仅包含您需要在详细信息视图上显示的属性。
domail 模型可能类似于:
public class Person
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
public string ExampleProperty1 { get; set; }
public string ExampleProperty2 { get; set; }
public string ExampleProperty3 { get; set; }
}
假设您只想显示此人的 id、名字、姓氏和年龄,那么您的视图模型将如下所示:
public class PersonDetailsViewModel
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
}
您不需要 ExampleProperty1、ExampleProperty2 和 ExampleProperty3,因为它们不是必需的。
您的人员控制器可能如下所示:
public class PersonController : Controller
{
private readonly IPersonRepository personRepository;
public PersonController(IPersonRepository personRepository)
{
// Check that personRepository is not null
this.personRepository = personRepository;
}
public ActionResult Details(int id)
{
// Check that id is not 0 or less than 0
Person person = personRepository.GetById(id);
// Now that you have your person, do a mapping from domain model to view model
// I use AutoMapper for all my mappings
PersonDetailsViewModel viewModel = Mapper.Map<PersonDetailsViewModel>(person);
return View(viewModel);
}
}
我希望这能让事情更清楚一点。