2012-03-29 45 views
1

MVC的新手,希望這會非常簡單。我有一個HTML下拉列表,我希望根據需要在聯繫人表單上設置,但是當我應用數據註釋時,我無法按照回覆的要求將它啓動。默認值是 「」如何根據需要在MVC3中設置下拉列表

這裏是我的HTML片段:

<div class="editor-field"> 
    <select name="ContactReason" size="1" class="textBox"> 
     <option value=""></option> 
     <option value="I have a question about this website">I have a question about this website</option> 
     <option value="My account is locked">My account is locked</option> 
     <option value="I am experiencing problems with the website">I am experiencing problems with the website</option> 
    </select> 
    @Html.ValidationMessageFor(m => m.ContactReason) 
</div> 

下面是我的註解我的C#代碼。我已經嘗試設置必要的屬性,甚至範圍屬性,但似乎都沒有辦法。

[Required(ErrorMessage = "Your reason for contacting is required.")] 
[Range(2, 100, 
ErrorMessage = "Your reason for contacting is required.")] 
public virtual string ContactReason { get; set; } 

感謝您的指導。

舊貨

回答

0

我發現下面的網站有所幫助:http://codeoverload.wordpress.com/2011/05/22/dropdown-lists-in-mvc-3/

我採取了以下和它的工作很適合我:

型號:

public List<SelectListItem> ContactReasons { get; set; } 

[Required(ErrorMessage = "Your reason for contacting is required.")] 
public virtual string ContactReason { get; set; } 

控制器:

public ActionResult Index() 
{ 
    var Model = new ContactForm(); 
    Model.ContactReasons = this.GetContactReasons(); 
    return View(Model); 
} 

private List<SelectListItem> GetContactReasons() 
{ 
    List<SelectListItem> items = new List<SelectListItem>(); 
    items.Add(new SelectListItem { Text = "", Value = "" }); 
    items.Add(new SelectListItem { Text = "I have a question about this website", Value = "I have a question about this website" }); 
    items.Add(new SelectListItem { Text = "I am experiencing problems with the website", Value = "I am experiencing problems with the website" }); 

    return items; 
} 

查看:

<div class="editor-label"> 
    @Html.Label("I am contacting because:") 
</div><br /> 
<div class="editor-field"> 
    @Html.DropDownListFor(m => m.ContactReason, Model.ContactReasons) 
    @Html.ValidationMessageFor(m => m.ContactReason) 
</div> 
1

使用在@ Html.DropDownListFor的optionLabel屬性()

讓它 「選擇一個」 或 「」(空字符串)

驗證在你的控制器標誌「選擇一」或‘’(空字符串)

做相同的JQuery