【发布时间】:2017-08-19 10:46:33
【问题描述】:
我有一个简单的下拉列表和一个文本框。当页面加载时,文本框被禁用。如果从下拉列表中选择“其他”,则启用文本框并将“必需”规则添加到文本框,因为我不希望用户在文本框中输入内容。选择“其他”并且如果单击“其他”,则可以看到验证错误消息,但在用户在空文本框中键入某些内容后,我无法删除该消息。这是它的外观:
这是我的模型:
using System.ComponentModel.DataAnnotations;
namespace validatetextbox.Models
{
public class Manager
{
public int Id { get; set; }
[Required]
public string City { get; set; }
[Display(Name = "Other City")]
[DisplayFormat(ConvertEmptyStringToNull = false)]
public string OtherCity { get; set; }
}
}
我的控制器方法是
// GET: Managers/Create
public ActionResult Create()
{
//populate Gender dropdown
List<SelectListItem> c = new List<SelectListItem>();
c.Add(new SelectListItem { Text = "-- Please Select --", Value = "" });
c.Add(new SelectListItem { Text = "New York", Value = "New York" });
c.Add(new SelectListItem { Text = "Miami", Value = "Miami" });
c.Add(new SelectListItem { Text = "Other", Value = "Other" });
ViewBag.Cities = c;
return View();
}
我的看法如下:
@model validatetextbox.Models.Manager
@{
ViewBag.Title = "Create";
}
<h2>Create</h2>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Manager</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.City, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownListFor(model => model.City, ViewBag.Cities as List<SelectListItem>, new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.City, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.OtherCity, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.OtherCity, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.OtherCity, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
<script type="text/javascript">
$(document).ready(function () {
$('#OtherCity').prop('disabled', true);
$('#City').change(function () {
if ($('#City option:selected').text() != 'Other') {
$("#OtherCity").rules("remove", "required");
$('#OtherCity').prop('disabled', true);
} else {
$('#OtherCity').prop('disabled', false)
$("#OtherCity").rules("add", "required");
}
});
});
</script>
}
【问题讨论】:
-
使用条件验证属性,例如foolproof
[RequiredIf]属性,以便您获得客户端和服务器端验证
标签: javascript c# jquery asp.net asp.net-mvc