2013-07-29 142 views
-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; } 
} 

VIEW

@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

負責接收提交的表單應該把你的模型參數的方法。只要你的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) 
+0

我如何可以使用自定義屬性功能 –

+0

這個忘記了,哈哈。更新了我的答案。 –

+0

嗯謝謝,但在我看來我有兩個控制之一是下拉式和其他文本框我想要訪問自定義屬性函數中的兩個值,所以我需要把兩個驗證屬性或一個.. –