开发者

MVC 3.0 ViewModels - Id Field is being Forcefully Required, even though I do not mark it [Required]

开发者 https://www.devze.com 2023-03-09 05:42 出处:网络
I have a ViewModel setup like so.. class PropertyViewModel { Guid Id { get; set;开发者_运维知识库 }

I have a ViewModel setup like so..

class PropertyViewModel {
   Guid Id { get; set;开发者_运维知识库 }

   [Required]
   [Regex ... ]
   string Name { get; set; }

   [Required]
   [Regex ... ]
   string Description { get; set; }
}

This ought to work fine. The reason for the Id field is because the model binder needs to have knowledge of the ID for editing later. But it will be rendered using a @Html.HiddenFor(model => model.Id). But for some reason, jQuery's Unobtrusive Validation is still flagging it as 'Required'.

Any idea why? And what I can do?


The .NET type System.Guid can never be null. You need to change your property to:

Guid? Id {get; set;}

You can read more about System.Guid here: http://msdn.microsoft.com/en-us/library/system.type.guid.aspx and about nullable types here: http://msdn.microsoft.com/en-us/library/2cf62fcy.aspx

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号