https://www.codeproject.com/tips/780992/asp-net-mvc-custom-compare-data-annotation-with-cl
修改Album.cs代码如下:
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; }
}
public virtual Genre Genre这种写法主要是延迟加载
[ScaffoldColumn(false)]
public int AlbumId { get; set; } 这个[ScaffoldColumn(false)] 主要是在在编辑表单页面Edit.cshtml是否生成这个字段的隐藏域,为True就生成,为False就不生成
为true的话就生成 @Html.HiddenFor(model => model.AlbumId),否则不生成。
[Bind(Exclude = "AlbumId")]
public class Album
在上面代码里加了Bind,意思是当表单提交值的时候是否包含在Model中, [Bind(Exclude = "AlbumId")]是排除。但是值得注意的是加了这个代码后,点击列表的编辑
然后在编辑表单点击提交修改后,会报错,因为Model里的AlbumId 被排除,然后控制器里的Action的Edit中的Model获取AlbumId老为0就报错了,
解决方法是去掉 [Bind(Exclude = "AlbumId")]