Shielding nullable domain properties with ViewModel

末鹿安然 提交于 2019-12-03 17:08:00

If you just need to display these fields in a View, you don't need to specify or check whether is has a value or not.

Using Model.Field1 in your View file is enough. It will simple not display anything, and it won't throw an exception. You can always use ?? to set a default when it makes sense.

@(Model.Field1 ?? "There is nothing to see here")

In most of the cases I use the "For" helpers, which seem OK with Nullable values (PublishedCount is a nullable property):

@Html.TextBoxFor(m => m.BillPull.PublishedCount, new { id="txtPublishedCount" })
@Html.ValidationMessageFor(m => m.BillPull.PublishedCount)

When I need to use just TextBox, I use the GetValueOrDefault method, with whatever default value the framework provides:

@Html.TextBox("BillPull.AutoPublishDate", Model.BillPull.AutoPublishDate.GetValueOrDefault().ToString(dateFormat), new { id = "dtpAutoPublishDate" })
@Html.ValidationMessageFor(m => m.BillPull.AutoPublishDate)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!