如何在ASP.NET MVC中使用ViewModels?
我刚开始学习ASP.NET MVC中的ViewModels。 所以,我想实现一个示例如下:
商业实体
public class AddModel { public int a { get; set; } public int b { get; set; } public int Add() { return (this.a + this.b); } }
添加ViewModel
public class AddViewModel { public AddModel addModel; public int Total { get; set; } }
调节器
public class AddController : Controller { [HttpPost] public JsonResult Add(AddViewModel model) { int iSum = model.addModel.a + model.addModel.b; model.Total = iSum; return Json(model); } public ActionResult Index() { return View(); } }
查看实施
@model ViewModelApplication.AddViewModel function Callback(data) { alert("I am sucess call"); } function Failed() { alert("I am a failure call"); } @using (Ajax.BeginForm("Add", "Add", new AjaxOptions { OnSuccess = "Callback", OnFailure = "Failed" })) { @Html.TextBoxFor(Model => Model.addModel.a) @Html.TextBoxFor(Model => Model.addModel.b)
}
这里的问题是,只要单击“ Add
按钮,我就无法检索输入到文本框中的值。 相应的AJAX动作就是它。
当我尝试访问a
和b
的值时,我得到空值而不是输入到文本框中的值。
我不知道我哪里出错了。 请帮忙。
您的视图模型应如下所示
public class AddViewModel { public int a { get; set; } public int b { get; set; } public int Total { get; set; } }
并在cshtml中
@Html.TextBoxFor(m=> ma) @Html.TextBoxFor(m=> mb)
在控制器中
[HttpPost] public JsonResult Add(AddViewModel model) { int iSum = model.a + model.b; model.Total = iSum; return Json(model); }
编辑
视图模型用于渲染您的视图不会在其中放置任何逻辑。 如果你有更复杂的模型,那么很难用ViewModel
映射Model
。 为此,您可以使用AutoMapper或ValueInjector在模型和视图模型之间进行映射。
自动关注链接http://automapper.codeplex.com/
价值注入器链接http://valueinjecter.codeplex.com/
希望这可以帮助
您不应在视图模型中使用域(业务)实体。 如果这样做,视图模型就没用了,因为它仍然包含您在视图中可能不需要的业务逻辑。 您的示例中的模型并不真正代表真实场景,无论如何都不需要视图模型。
一个更常见和简单的视图模型示例是登录表单:您可能有一个名为User
的域模型,您希望它们登录。 User
域模型可能很大,只需要一小部分进行身份validation。 它还包含数据库的validation逻辑,它不代表登录表单的validation逻辑。
User
域模型:
public class User { [Required] public string UserName { get; set; } [Required] [MaxLength(36)] // The password is hashed so it won't be bigger than 36 chars. public string Password { get; set; } public string FullName { get; set; } public string SalesRepresentative { get; set; } // etc.. }
上述域模型表示数据库表,因此包含validation逻辑以确保完整性。
public class LoginModel { [Display(Name = "User Name")] [Required(ErrorMessage = "Please fill in your user name.")] public string UserName { get; set; } [Required(ErrorMessage = "Please fill in your password.")] public string Password { get; set; } public bool RememberMe { get; set; } }
上面的视图模型仅包含登录表单所需的属性,并具有自己的数据注释。 这有助于您清晰地分离视图逻辑和业务/数据逻辑。