ASP.NET MVC模型绑定——绑定部分字段
2013-01-20 12:27
513 查看
using System; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; namespace Xautjzd.Models {
[Bind(Exclude="CollectionStationId, ContactInfo ")] //排除一部分字段,只绑定模型中的部分字段 public class ServeStation { [Key] [DisplayName("服务站编号")] public string ServeStationId { get; set; } [DisplayName("服务站")] [Required] public string ServeStationName { get; set; } [DisplayName("集货点编号")] [Required] public string CollectionStationId { get; set; } [DisplayName("站长")] [Required] public string ServeStationManager { get; set; } [DisplayName("联系方式")] [Required] public string ContactInfo { get; set; } [DisplayName("乡镇")] [Required] public string Town { get; set; } [DisplayName("总站名称")] [Required] public string StationName{ get; set; } [DisplayName("所管辖区业务经理")] [Required] public string RegionBusinessManager { get; set; } [DisplayName("所管辖区总经理")] [Required] public string StationManger { get; set; } [DisplayName("备注")] [Required] public string Note { get; set; } } }
Bind虽可以限制绑定的字段,但是模型验证却无法通过,因为模型验证在Submit后Action执行前完成,所以就会无法通过ModelState.IsValid验证值判断到底验证是否成功。
尽管如此,我们还是可以通过ModelState["字段名称"]语句来判断是否发生了错误,但如此做会让ASP.NET MVC变得很不方便。
于是乎ASP.NET MVC的Controller类提供了TryUpdateModel方法来解决这个问题,eg:
if(!TryUpdateModel(serveStation)) { //验证失败 return View(); } db.saveChanges(); return View("Index");
注:可用ModelState.addModelError("模型字段名","验证失败的错误信息");来手动添加验证失败时的错误提示信息
相关文章推荐
- asp.netMVC中的自动绑定模型测试小结
- ASP.NET MVC 常用扩展点:过滤器、模型绑定等
- ASP.NET没有魔法——ASP.NET MVC 模型绑定
- ASP.NET Core MVC/WebAPi 模型绑定探索
- ASP.NET MVC 5 (二)动态输出、辅助器方法、模型绑定与添加验证
- ASP.NET MVC 常用扩展点:过滤器、模型绑定等
- ASP.NET MVC中 Jquery AJAX 获取数据利用MVC模型绑定实现输出
- ASP.NET MVC 5 - 给电影表和模型添加新字段
- ASP.NET MVC 模型绑定的 6 个建议
- ASP.NET MVC保持表单数据状态的方法:input辅助器+模型绑定
- 详解ASP.NET MVC 常用扩展点:过滤器、模型绑定
- asp.net Mvc 模型绑定项目过多会导致页面运行时间卡
- Asp.net MVC 3 Framework 第十七章 模型绑定
- ASP.NET MVC学习三-数据传递之模型绑定
- 《ASP.NET MVC 4 实战》学习笔记 11:模型绑定器与值提供器
- ASP.NET Core MVC/WebAPi 模型绑定
- ASP.NET MVC数组模型绑定
- ASP.NET MVC 视图与模型绑定
- ASP.NET MVC 4 (九) 模型绑定
- Asp.Net MVC在过滤器中使用模型绑定