Overload EF Validation with Custom class
I m using Entity Framework, and have one view which is strongly type view model of type tblAuthorMaster. On Post ModelState returns me following error :
The value '0' is not valid for Status.
Here Status is of boolen datatype in DB/EF and on view it's dropdown (TEXT="active/inactive", VALUE="1/0"), so whenever i post my form i used to get the above error message.
I have tried some solution to overcome with this issue but it seems not wotking properly.
Following is my code base:
Here tblAuthorMaster is EF Class and AuthorModel is my Custom Class, which im using for some custom validation and other stuff.
[MetadataType(typeof(AuthorModel))] public partial class tblAuthorMaster { } public class AuthorModel { [Required(ErrorMessage = "*")] public string AuthorName { get; set; } [Required(ErrorMessage = "*")] public bool Status { get; set; } }
Thanks in advance.
For this to work properly the VALUE in the dropdown must be true/false
and not 1/0
. Since you haven't shown how you are generating your doropdown it is hard to help but it might look something like this:
<%= Html.DropDownListFor(
x => x.Status,
new[]
{
new SelectListItem { Value = "true", Text = "active" },
new SelectListItem { Value = "false", Text = "inactive" },
}
) %>
Also what's the point of using a dropdown with 2 possible values? HTML provides you with checkboxes for this purpose:
<%= Html.CheckBoxFor(x => x.Status) %>
And a final remark: what you call a view model in your question is not a view model at all. It's an autogenerated EF domain model. View models are classes tat you specifically design for the requirements of a given view, they are not autogenerated by some wizard.
链接地址: http://www.djcxy.com/p/56578.html上一篇: 具有多个参数的自定义验证属性
下一篇: 使用自定义类重载EF验证