.Net MVC无法使用jQuery删除验证消息

时间:2017-08-19 10:46:34

标签: javascript c# jquery asp.net asp.net-mvc

我有一个简单的下拉列表和一个文本框。页面加载时,文本框被禁用。如果从下拉列表中选择“其他”,则启用文本框并将“必需”规则添加到文本框中,因为我不希望用户在文本框中输入内容。选择“其他”并单击“创建”按钮时,我可以看到验证错误消息,但在用户在空文本框中键入内容后,我无法删除该消息。以下是它的外观:

enter image description here

这是我的模特:

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>

}

1 个答案:

答案 0 :(得分:0)

要保留现有代码,您可以从文档准备好的文本框中remove the rules。另外 - 旁注 - 保持引号一致。

<script type="text/javascript">
    $(document).ready(function () {
        $('#OtherCity').prop('disabled', true);
        // Remove any rules
        $('#OtherCity').rules("remove");
        $('#City').change(function () {
            if ($('#City option:selected').text() != 'Other') {
                //Also tidy up `"` to `'`
                $('#OtherCity').rules("remove", "required");
                $('#OtherCity').prop('disabled', true);
            } else {
                $('#OtherCity').prop('disabled', false)
                //Also tidy up `"` to `'`
                $('#OtherCity').rules("add", "required");
            }
        });
    });
</script>

您可以尝试的另一件事是 - 将类可选添加到编辑器中 - 标签将显示,可见性和验证要求将由JS控制:

<div class="form-group">
    @Html.LabelFor(model => model.OtherCity, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10 optional">
        @Html.EditorFor(model => model.OtherCity, new { htmlAttributes = new { @class = "form-control" } })
        @Html.ValidationMessageFor(model => model.OtherCity, "", new { @class = "text-danger" })
    </div>
</div>

$(document).ready(function () {
    // This will hide the field
    $('.optional').hide();
    // This makes the value optional
    $('#OtherCity').attr("data-val", "false");
    $('#City').change(function () {
        if ($('#City option:selected').text() == 'Other') {
            // Show the text editor
            $('.optional').show();
            // This makes the value required
            $('#OtherCity').attr("data-val", "true");

        } else {
            $('.optional').hide();
            $('#OtherCity').attr("data-val", "false");
        }
    });
});