MVC3 Dropdownlist - String / Role Value
Ok here is my challenge: I want to create a dropdownlist with three strings in my Register View - "Please Select", "I am a client", and "I am a vendor". When the user selects the "I am a client" and submits he is added to the "Client" role. When the user selects the "I am a Vendor" role he is added to the "Vendor" role. If the user doesn't select either and leaves on "Please select" validation occurs.
I can get the roles to directly populate via the ViewBag. Here's how:
Register.cshtml - <div class="editor-label">
@Html.LabelFor(m => m.Role, "I am a:")
</div>
<div class="editor-field">
@Html.DropDownList("Role", ViewBag.Roles as SelectList,"Please Select")
</div>
AccountModel.cs -
public class RegisterModel
{
[Required]
[Display(Name = "Role")]
public string Role { get; set; }
AccountController.cs -
public ActionResult Register()
{
ViewBag.Roles = new SelectList(Roles.GetAllRoles().ToList());
return View();
What I still need to accomplish -
Currently the dropdownlist only populates the actual roles. This is not what I want though.
How do I instead create a dropdownlist for three strings in my Register View - "Please Select", "I am a clien开发者_运维技巧t", and "I am a vendor".
I have no hair left on this one and will be grateful to anyone who can help me to figure this one out. Thanks.
Something similar to below would work perfectly:
public class RegisterModel
{
[Required]
[Display(Name = "Role")]
public string Role { get; set; }
Then you can have something similar to this in your view.
@Html.DropDownListFor(x => x.Role, new[] {
new SelectListItem() {Text = "I am a vendor", Value = "Vendor"},
new SelectListItem() {Text = "I am a client", Value = "Client"}
}, "Pick a basket")
Edit: String is a reference type and is nullable by default.
You can set the list values in the constructor: SelectList(dataObjects, valueField, textField)
ViewBag.Roles = new SelectList(Roles.GetAllRoles().ToList(), "Id", "Name");
This allows you to define what attributes of your Role objects are being set as the values and texts of the options.
精彩评论