我有一个需要填写必填字段的日期选择器文本框。模型:
[Required(AllowEmptyStrings = false, ErrorMessage = "Required")]
[DisplayFormat(ConvertEmptyStringToNull = false)]
[Display(Name = "Date of Something")]
[DatePicker] //custom tag builder I wrote to make this a datepicker
public string DateOfSomething { get; set; }
看法:
@Html.ControlGroupFor(x => x.DateOfSomething) //has the custom tag I built to handle datepicker
@Html.ValidationMessageFor(x => x.DateOfSomething)
jQuery:
$("#btnSubmit").click(function() {
if ($('#DateOfSomething') == "" || $('#DateOfSomething') == null) {
$("#ValidationSummary").append("<div>Required</div>");
$("#ValidationSummary").show();
}
});
在 _layout 中
<script src="@Url.Content("~/Scripts/jquery-1.9.1.min.js")"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive-custom-for-bootstrap.js")"></script>
控制组扩展:
public static MvcHtmlString ControlGroupFor<TModel, TValue>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TValue>> expression)
{
var propertyName = ExpressionHelper.GetExpressionText(expression);
var controlGroupWrapper = BuildTagWith("div", "control-group");
controlGroupWrapper.InnerHtml += htmlHelper.LabelFor(expression, new Dictionary<string, object> { { "class", "control-label" } }).ToHtmlString();
var controlDiv2 = BuildTagWith("div", "controls");
var metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
var inputTag = "";
var valAttributes = htmlHelper.GetUnobtrusiveValidationAttributes(propertyName, metadata);
if (metadata.AdditionalValues.ContainsKey("DatePicker"))
{
CreateDatePicker(htmlHelper, expression, propertyName, controlDiv2, controlGroupWrapper);
controlGroupWrapper.InnerHtml += htmlHelper.ValidationMessageFor(expression, null, valAttributes);
return MvcHtmlString.Create(controlGroupWrapper.ToString(TagRenderMode.Normal));
}
if (metadata.AdditionalValues.ContainsKey("DropDownListPropertyName"))
{
var propertyNameForOptions = metadata.AdditionalValues["DropDownListPropertyName"] as string;
var options = GetPropValue(htmlHelper.ViewData.Model, propertyNameForOptions) as Dictionary<string, string>;
var selectedItem = GetPropValue(htmlHelper.ViewData.Model, propertyName) as string;
inputTag += BuildSelectList(options, propertyName, selectedItem);
}
else
{
var value = GetPropValue(htmlHelper.ViewData.Model, propertyName);
inputTag += htmlHelper.EditorFor(expression).ToHtmlString();
}
controlDiv2.InnerHtml += inputTag + htmlHelper.ValidationMessageFor(expression, null, valAttributes);
controlGroupWrapper.InnerHtml += controlDiv2.ToString(TagRenderMode.Normal);
return MvcHtmlString.Create(controlGroupWrapper.ToString(TagRenderMode.Normal));
}
尽管我的代码试图阻止它,但我还是发布到表单。有任何想法吗?