我有一个datepicker文本框,我需要创建一个必填字段。 型号:
[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>
ControlGroupFor扩展名:
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));
}
尽管我的代码试图阻止它,但我发布到表单。任何想法?
答案 0 :(得分:1)
尝试删除click
处理程序。该javascript应该是不必要的,因为它应该由jQuery验证和Required
属性处理。如果一个或多个字段无效,jQuery验证还会处理取消提交。
答案 1 :(得分:0)