我在
中使用MVC4进行基于自定义属性的验证我可以使用propertyinfo []
使用以下代码在文本框中输入用户输入的值PropertyInfo textBoxEnteredValue = validationContext.ObjectType.GetProperty("TxtCrossField");
但我无法获得用户选择的下拉值。
是否需要进行任何代码更改,请提示
object value
在IsValid
方法中为NULL。知道为什么会这样吗?
验证
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
//Working
PropertyInfo textBoxEnteredValue = validationContext.ObjectType.GetProperty("TxtCrossField");
//How to get the selected item?
PropertyInfo selectedDropdownlistvalue = validationContext.ObjectType.GetProperty("DDlList1");
}
模型
public class CrossFieldValidation
{
public string DDlList1
{ get; set; }
// [Required(ErrorMessage = "Quantity is required")]
[ValueMustbeInRange]
[Display(Name = "Quantity:")]
public string TxtCrossField
{ get; set; }
}
查看
@model MvcSampleApplication.Models.CrossFieldValidation
@{
ViewBag.Title = "DdlCrossFields";
}
<h2>DdlCrossFields</h2>
@using (Html.BeginForm("PostValues", "CrossFieldsTxtboxes"))
{
@Html.ValidationSummary(true)
<div class ="editor-field">
@Html.TextBoxFor(m => m.TxtCrossField)
@Html.ValidationMessageFor(m=>m.TxtCrossField)
</div>
@*@Html.DropDownList("DDlList1",(IEnumerable<SelectListItem>)ViewBag.itemsforDropdown)*@
@Html.DropDownList("ItemsforDrop", ViewBag.ItemsforDrop as SelectList,"Select A state", new {id= "State"})
<input id="PostValues" type="Submit" value="PostValues" />
}
任何人都会建议任何关于这一点的想法...... 非常感谢....
答案 0 :(得分:0)
负责接收已发布表单的方法应将您的模型作为参数。只要您的DDL绑定到该模型中的属性,您就可以获得所选的值,如下所示:
<强>控制器强>
[...some attributes...]
public static void MethodInController(YourModelType model)
{
var selectedValue = model.DropDownListSelectedValue;
}
<强>模型强>
public class YourModelType
{
public List<SomeType> DropDownOptions { get; set; }
[YourValidationAttribute]
public string DropDownListSelectedValue { get; set; }
}
验证属性类
public class YourValidationAttribute : ValidationAttribute
{
public override bool IsValid(object value)
{
//return based on conditions of "value"
}
}
查看强>
@Html.DropDownListFor(model => model.DropDownListSelectedValue, model.DropDownListOptions)