在MVC中使用ViewMode [英] Use of ViewMode in MVC

查看:56
本文介绍了在MVC中使用ViewMode的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在asp.net中使用View Model mvc

How to use View Model in asp.net mvc

推荐答案

声明类。创建实例 - 通常使用数据模型中的选择和投影填充列表或单个对象。将它传递给一个动作的视图,在视图中使用。

但是如果你自己找不到类似的东西,这里有一些教程: http://www.dotnet-tricks.com/Tutorial/mvc/QHQT270712-Understanding-ViewModel- in-ASP.NET-MVC.html [ ^ ], http://sampathloku.blogspot.fr/2012/10/how-to-use-viewmodel-with-aspnet-mvc.html [ ^ ]
Declare class. Create instances - usually populating lists or individual objects with selection and projection from data model. Pass it to the view from an action, use in the view.
But here are some tutorials if you couldn't find something like them on your own: http://www.dotnet-tricks.com/Tutorial/mvc/QHQT270712-Understanding-ViewModel-in-ASP.NET-MVC.html[^], http://sampathloku.blogspot.fr/2012/10/how-to-use-viewmodel-with-aspnet-mvc.html[^]


视图模型是一个表示特定视图中使用的数据模型的类。我们可以使用这个类作为登录页面的模型:



公共类LoginPageVM

{

[必需(ErrorMessage =您是否真的尝试登录而不输入用户名?)]

[DisplayName(用户名/电子邮件)]

公共字符串UserName {得到;组; }

[必填(ErrorMessage =请输入密码:))]

[DisplayName(密码)]

公共字符串密码{get;组; }

[DisplayName(关闭浏览器时保持登录状态)]

public bool RememberMe {get;组; }

}

使用此视图模型,您可以定义视图(Razor视图引擎):



@ model CamelTrap.Models.ViewModels.LoginPageVM



@using(Html.BeginForm()){

@ Html.EditorFor(m => ; m);

< input type =submitvalue =Saveclass =submit/>

}

行动:



[HttpGet]

public ActionResult LoginPage()

{

返回查看();

}



[HttpPost]

公共ActionResult LoginPage(LoginPageVM模型)

{

...登录用户申请代码...

返回查看(型号);

}
View model is a class that represents the data model used in a specific view. We could use this class as a model for a login page:

public class LoginPageVM
{
[Required(ErrorMessage = "Are you really trying to login without entering username?")]
[DisplayName("Username/e-mail")]
public string UserName { get; set; }
[Required(ErrorMessage = "Please enter password:)")]
[DisplayName("Password")]
public string Password { get; set; }
[DisplayName("Stay logged in when browser is closed")]
public bool RememberMe { get; set; }
}
Using this view model you can define the view (Razor view engine):

@model CamelTrap.Models.ViewModels.LoginPageVM

@using (Html.BeginForm()) {
@Html.EditorFor(m => m);
<input type="submit" value="Save" class="submit" />
}
And actions:

[HttpGet]
public ActionResult LoginPage()
{
return View();
}

[HttpPost]
public ActionResult LoginPage(LoginPageVM model)
{
...code to login user to application...
return View(model);
}


这篇关于在MVC中使用ViewMode的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆