MVC3 HTMLHelper defaults

隐身守侯 提交于 2019-12-02 04:15:28

问题


I have an html helper that I'd like to set a default on.

@Html.EditorFor(model => model.DateFrom)

What's the syntax to set the default value of the helper if the model.DateFrom is null?


回答1:


I dont think that using EditorFor you can set a default value. Consider setting it in the accessors on your model?

To do it on other types ( TextBoxFor etc ) You can set a value but not a default value. So you would need to do:

@if(Model.something == null)
{
   @Html.TextBoxFor(m => m.ID, new { @Value = "Value!"})
} else {
   @Html.TextBoxFor(m => m.ID)
}

As I would reccomend:

private DateTime? _date;
public DateTime? date {
get {
   if(_date == null)
      _date = DateTime.Now;
   return _date;
}
set {
   _date = value;
}
}

Using things such as jquery date picker allow you to have a default value if the problem is that you are just posting nothing back if it has not been selected.




回答2:


I believe the only HTML Helper that supports a default value is the Html.DropDownList(). It has an optionLabel parameter that allows you to set the default option at the top of the dropdown list. For example:

Html.DropDownList("CustomerId", "Select a Customer")

As Henry, mentioned if you would like to set a default value on other HTML helpers, set it within the model or roll your own helper.



来源:https://stackoverflow.com/questions/7891519/mvc3-htmlhelper-defaults

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!