[英]Update validation on an automatically selected dropdown list value
在MVC表单上,我有两个下拉菜单:“水果”和“颜色”。 水果下拉列表由控制器填充。 根据“水果”下拉列表中选择的值,使用“ 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");
}
}
视图
<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();
那对你有用吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.