正在获取用户选择的下拉值

本文关键字:选择 获取 用户 | 更新日期: 2023-09-27 18:25:17

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

我可以使用propertyinfo[]使用以下代码在文本框中获取用户输入的值

PropertyInfo textBoxEnteredValue = validationContext.ObjectType.GetProperty("TxtCrossField");

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

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

  2. object value作为NULL进入IsValid方法。知道为什么会这样吗?

验证

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

请任何人对此提出任何想法。。。非常感谢。。。。

正在获取用户选择的下拉值

负责接收已发布表单的方法应该将您的模型作为参数。只要您的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)