开发者

How to handle nulls in ASP.NET MVC

I have user registration form. It has field Date of birth. It is not compulsory in database also not on UI. But while create when i am goiing to assign it to objects property, i have to convert it in to date format. But if i have not selected it, it will become null in the FormCollection object. like

User.DOB=Convert.ToDateTime(collection["DOB"]);

Now issue is if it collection["DOB"]is null then it throw开发者_StackOverflow中文版s exception. I can not assign default value here. So how can i handle this situation?


You'll probably be better off using DateTime.TryParse for this.

This way you can check whether you're working with a valid date or not.

DateTime dateOfBirth;

bool isValidDateOfBirth = DateTime.TryParse(collection["DOB"], out dateOfBirth);

if(isValidDateOfBirth)
{
 // do stuff
}
else
{
 // do some other stuff
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜