-1

我有一个使用 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" />
}

有没有人请提出任何关于这个的想法...非常感谢....

4

1 回答 1

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)
于 2013-07-29T14:35:53.803 回答