在谈论表单验证时,作者说Bind anntoations用于:
Lists fields to exclude or include when binding parameter or form values to model properties
这对我来说有点胡言乱语 – 我不明白.它究竟意味着什么?也许问题是脚手架这个词在字典中的含义与IT没有任何联系.
结果是什么:[Bind(Exclude =“AlbumId”)]和键入的意义是什么:[ScaffoldColumn(false)] – 默认情况下不隐藏该列,为什么要再说一遍.
namespace MvcMusicStore.Models { [Bind(Exclude = "AlbumId")] public class Album { [ScaffoldColumn(false)] public int AlbumId { get; set; } [displayName("Genre")] public int GenreId { get; set; } [displayName("Artist")] public int ArtistId { get; set; } [required(ErrorMessage = "An Album Title is required")] [StringLength(160)] public string Title { get; set; } [required(ErrorMessage = "Price is required")] [Range(0.01,100.00,ErrorMessage = "Price must be between 0.01 and 100.00")] public decimal Price { get; set; } [displayName("Album Art URL")] [StringLength(1024)] public string albumartUrl { get; set; } public virtual Genre Genre { get; set; } public virtual Artist Artist { get; set; } } }
解决方法
值得一提的是,我已经在ASP.NET MVC上构建应用程序已经超过两年了,而不是曾经使用过ScaffoldColumn属性.但是,要实际回答您的问题,该属性用于告诉框架该字段是否应该可见.
例如,如果您使用了@ Html.EditorForModel()(此方法在引擎盖下做了一些魔术并构建了模型属性的表单输入),那么您的视图将不包含ScaffoldColumn属性中标记为false的列的输入.它本质上是一种快捷方式,告诉框架在构建视图时不允许编辑字段.同样,我从不使用EditorForModel,因为我为每个输入手动构建了我的表单,因为我想要更精细的控制.
捆绑
Bind属性用于告诉框架是否要在将数据发送到服务器时允许绑定属性(这更像是一个安全功能).
考虑这个动作:
[HttpPost] public ActionResult DontSendMetooMuchData(Employee employee) { db.Employees.Update(employee); }
假设Employee对象如下所示:
public class Employee { public string FirstName { get; set; } public string LastName { get; set; } public string SocialSecurityNumber { get; set; } }
现在假设我发送一个发送数据的HTTP POST请求:
FirstName=Justin &LastName=Helgerson &SocialSecurityNumber=YouShouldntLetMeUpdateThis
您刚刚更新了我的社会安全号码!坏消息.你怎么阻止它?
[Bind(Exclude = "SocialSecurityNumber")] public class Employee { public string FirstName { get; set; } public string LastName { get; set; } public string SocialSecurityNumber { get; set; } }
现在,当执行DontSendMetooMuchData方法并且ASP.NET MVC执行模型绑定以从HTTP请求中提供Employee对象时,将永远不会从请求数据填充SocialSecurityNumber属性.
同样,这是我从未在我的应用程序中使用的属性.还有另一种解决这个问题的方法,它有其他好处.由于担心这个答案变得太长,解决问题的方法是为您的视图和数据库使用不同的模型.我从不让我的数据库对象出现在我的视野中.相反,我构建了一个专门用于视图的类,它只包含我希望用户提供的属性.
原文地址:https://www.jb51.cc/java/126409.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。