2012-03-29 69 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

相关问题