获取用户选择的下拉值

时间:2013-07-29 14:11:03

标签: c# asp.net-mvc asp.net-mvc-3 asp.net-mvc-4

我在

中使用MVC4进行基于自定义属性的验证

我可以使用propertyinfo []

使用以下代码在文本框中输入用户输入的值
PropertyInfo textBoxEnteredValue = validationContext.ObjectType.GetProperty("TxtCrossField");

但我无法获得用户选择的下拉值。

  1. 是否需要进行任何代码更改,请提示

  2. object valueIsValid方法中为NULL。知道为什么会这样吗?

  3. 验证

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

    任何人都会建议任何关于这一点的想法...... 非常感谢....

1 个答案:

答案 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)