我为出生日期创建了自定义助手,如下所示。
自定义 Html Helper 方法
public static MvcHtmlString DateOfBirthFor(this HtmlHelper html, string id ,int minYear, int maxYear, object htmlAttribute = null)
{
RouteValueDictionary attributes = new RouteValueDictionary(htmlAttribute);
var days = Enumerable.Range(1, 31).Select(x => new SelectListItem
{
Value = x.ToString(),
Text = x.ToString()
});
var months = Enumerable.Range(1, 12).Select(x => new SelectListItem
{
Value = x.ToString(),
Text = x.ToString()
});
var years = Enumerable.Range(minYear, maxYear-(minYear-1)).Select(x => new SelectListItem
{
Value = x.ToString(),
Text = x.ToString()
});
var mainDivTag = new TagBuilder("div");
mainDivTag.MergeAttribute("id", id);
mainDivTag.MergeAttributes(attributes);
mainDivTag.InnerHtml = string.Concat(
html.DropDownList("Day", days, new { style="width : 40px "}).ToHtmlString(),
html.DropDownList("Month", months, new { style = "width : 40px " }).ToHtmlString(),
html.DropDownList("Year", years, new { style = "width : 60px " }).ToHtmlString()
);
return new MvcHtmlString(mainDivTag.ToString());
}
我还为同一个控件编写了自定义活页夹。
protected override void BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, System.ComponentModel.PropertyDescriptor propertyDescriptor)
{
if (propertyDescriptor.Name == "DateOfBirth")
{
DateTime dob = new DateTime(int.Parse(controllerContext.HttpContext.Request.Form["Year"]), int.Parse(controllerContext.HttpContext.Request.Form["Month"]), int.Parse(controllerContext.HttpContext.Request.Form["Day"]));
propertyDescriptor.SetValue(bindingContext.Model, dob);
}
}
但是,现在我必须为同一个控件制作强烈的自定义助手。所以,我不必编写自定义绑定。