更新对自动选择的下拉列表值的验证

本文关键字:下拉列表 验证 选择 更新 | 更新日期: 2023-09-27 18:18:57

在MVC表单上我有两个下拉框:水果和颜色。Fruit下拉框由控制器填充。颜色下拉框是根据水果下拉框中选择的值用Jquery填充的。水果下拉菜单中只有两个选项:苹果或香蕉。如果选择Apple,则会在颜色下拉菜单中出现两个选择:红色或绿色。如果选择香蕉色,则自动选择黄色。

一切都很好,除了当我试图添加验证。在提交时,如果在任何一个下拉框中都没有选择值,则在每个未选中的下拉框旁边显示一条消息。然后,当选择一个值时,消息将消失。当手动选择值时,这工作得很好,但是当颜色下拉框中的值通过代码自动选择时,消息不会消失。只有当我单击下拉菜单时,该消息才会消失——就像直到手动选择该值时才实际选择该值一样。

如何使自动选择的下拉菜单像手动选择的下拉菜单一样?

public class FruitVm
{
    public Fruit Fruit { get; set; }
    public Color Color { get; set; }
    public List<Fruit> FruitList { get; set; }
    public List<Color> ColorList { get; set; }
}
public class Fruit
{
    [MustBeSelectedAttribute(ErrorMessage = "Please Select Fruit")]   
    public int Id { get; set; } 
    public string Name { get; set; }
}
public class Color
{
    [MustBeSelectedAttribute(ErrorMessage = "Please Select Color")]   
    public int Id { get; set; }
    public string Name { get; set; }
}
public class MustBeSelectedAttribute : ValidationAttribute, IClientValidatable // IClientValidatable for client side Validation
{
    public override bool IsValid(object value)
    {
        if (value == null || (int)value == 0)
            return false;
        else
            return true;
    }
    // Implement IClientValidatable for client side Validation
    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        return new ModelClientValidationRule[] { new ModelClientValidationRule { ValidationType = "dropdown", ErrorMessage = this.ErrorMessage } };
    }
}
控制器

public class FruitController : Controller
{
    //
    // GET: /Fruit/
    FruitVm model = new FruitVm();
    public List<Fruit> GetFruits()
    {
        List<Fruit> FruitList = new List<Fruit>();
        FruitList.Add(new Fruit 
        { 
            Id = 1,
            Name = "Apple"
        });
        FruitList.Add(new Fruit 
        { 
            Id = 2,
            Name = "Banana"
        });
        return FruitList;
    }
    public List<Color> GetColors(int id)
    {
        List<Color> ColorList = new List<Color>();
        if (id == 1)
        {
            ColorList.Add(new Color
            {
                Id = 1,
                Name = "Red"
            });
            ColorList.Add(new Color 
            {
                Id = 2,
                Name = "Green"
            });
            return ColorList;
        }
        else if (id == 2)
        {
            ColorList.Add(new Color
            {
                Id = 3,
                Name = "Yellow"
            });
            return ColorList;
        }
        else
        {
            return null;
        }
    }
    [HttpPost]
    public ActionResult Colors(int id)
    {
        var colors = GetColors(id);
        return Json(new SelectList(colors, "Id", "Name"));
    }
    public ActionResult Index()
    {
        model.FruitList = GetFruits();
        model.ColorList = new List<Color>();
        return View(model);
    }
    [HttpPost]
    public ActionResult Index(FruitVm tmpModel)
    {
        return RedirectToAction("Index");
    }
}
<<p> 视图/strong>
<script type="text/javascript">
    jQuery.validator.unobtrusive.adapters.add("dropdown", function (options) {
        //  debugger;
        if (options.element.tagName.toUpperCase() == "SELECT" && options.element.type.toUpperCase() == "SELECT-ONE") {
            options.rules["required"] = true;
            if (options.message) {
                options.messages["required"] = options.message;
            }
        }
    });
    $(document).ready(function () {
        $("#Fruit_Id").change(function () {
            var id = $(this).val();
            getColors(id);
        })
    })
    function getColors(id) {
        $.ajax({
            url: "@Url.Action("Colors", "Fruit")",
            data: { id: id },
            dataType: "json",
            type: "POST",
            error: function () {
                alert("An error occurred");
            },
            success: function (data) {
                var colors = "";
                var numberOfColors = data.length;
                if (numberOfColors > 1) {
                    colors += '<option value="">-- select color --</option>';
                }
                $.each(data, function (i, color) {
                    colors += '<option value="' + color.Value + '">' + color.Text + '</option>';
                })                
                $("#Color_Id").empty().append(colors);
            }
        })
    }
</script>
@using (Html.BeginForm())
{
    <fieldset>
        <legend>Fruits Dropdowns</legend>
        <ol>
            <li>
                @Html.DropDownListFor(
                    x => x.Fruit.Id,
                    new SelectList(Model.FruitList, "Id", "Name"),
                    "-- select fruit --")
                @Html.ValidationMessageFor(x => x.Fruit.Id)
            </li>
            <li>
                @Html.DropDownListFor(                    
                    x => x.Color.Id,
                    new SelectList(Model.ColorList, "Id", "Name"),
                    "-- select color --")
                @Html.ValidationMessageFor(x => x.Color.Id)
            </li>
        </ol>
        <input type="submit" value="Submit" />
    </fieldset>
}

更新对自动选择的下拉列表值的验证

尝试使用:

强制重新验证
$("form").validate();

这对你有用吗?