私は単純な形式のドロップダウンリストとテキストボックスを持っています。ページが読み込まれると、テキストボックスは無効になります。ドロップダウンリストから「その他」を選択すると、テキストボックスが有効になり、ユーザーがテキストボックスに何かを入力しないようにするために、「必須」ルールをテキストボックスに追加します。 'Other'を選択し、Createボタンをクリックすると、検証エラーメッセージが表示されますが、ユーザーが空のテキストボックスに何かを入力した後でそのメッセージを削除することはできません。ここではそれがどのように見えるかです:ここでは.Net MVC jQueryを使用してValdationメッセージを取り除くことができません。
は私のモデルである:
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](http://foolproof.codeplex.com/) '[RequiredIf]'属性 –