Foo*_*Foo 3 asp.net-mvc asp.net-mvc-4
我是asp.net mvc的新手.我有这个控制器,它接受一些参数,然后返回一个视图,根据输入参数获取数据.
我想接受输入参数作为对象(例如,而不是名字,姓氏和年龄,我想要一个具有这三个参数作为其属性的人类).现在我的问题是输入参数类(Person类)是否有资格被称为视图模型?如是.我是否将返回视图模型作为此类的一部分?
换句话说,底部两种方法中的哪一种是优选的
案例1:输入和返回的相同类
public ActionResult GetPersonDetails(Person p)
{
return View(new Person {....})
}
Run Code Online (Sandbox Code Playgroud)
案例2:输入和返回的单独类
public ActionResult GetPersonDetails(Person p)
{
return View(new PersonDetails {....})
}
Run Code Online (Sandbox Code Playgroud)
现在我的问题是输入参数类(Person类)是否有资格被称为视图模型?
是.
如是.我是否将返回视图模型作为此类的一部分?
不必要.您可以将传递给视图的不同视图模型作为控制器操作作为参数的视图模型,尽管这是罕见的情况.这实际上取决于您的具体情况,但一般模式如下:
[HttpGet]
public ActionResult Index()
{
MyViewModel model = ...
return View(model);
}
[HttpPost]
public ActionResult Index(MyViewModel model)
{
if (!ModelState.IsValid)
{
// Some validation error occurred => redisplay the same view so
// that the user can fix his errors
return View(model);
}
// at this stage the view model has passed all validations =>
// here you could attempt to pass those values to your backend
// TODO: do something with the posted values like updating a database or something
// Finally redirect to a successful action Redirect-After-Post pattern
// http://en.wikipedia.org/wiki/Post/Redirect/Get
return RedirectToAction("Success");
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1448 次 |
| 最近记录: |