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

时间:2014-08-21 17:18:27

标签: c# jquery asp.net-mvc

在MVC表格中,我有两个下拉菜单:水果和颜色。 Fruit下拉列表由控制器填充。根据在Fruit下拉列表中选择的值,使用Jquery填充Color下拉列表。 Fruit下拉菜单中只有两个选项:Apple或Banana。如果选择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");
    }

}

查看

<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>
}

1 个答案:

答案 0 :(得分:0)

尝试使用以下方法强制重新验证:

$("form").validate();

这对你有用吗?