I created a controller which accepts one parameter from query string, this parameter is an integer, and i have a drop down list , i want to set a default value from the list based on the parameter value , but it's not working. I am using DropDownListFor
html helper to create the list.
Here is my controller:
public ActionResult Index(int accountType)
{
List<SelectListItem> listItems = new List<SelectListItem>
{
new SelectListItem{Text = "Competitor",Value = "Competitor"},
new SelectListItem{Text = "Consultant",Value = "Consultant"},
new SelectListItem{Text = "Customer",Value = "Customer"},
new SelectListItem{Text = "Investor",Value = "Investor"},
new SelectListItem{Text = "Partner",Value = "Partner"},
new SelectListItem{Text = "Influencer",Value = "Influencer"},
new SelectListItem{Text = "Press",Value = "Press"},
new SelectListItem{Text = "Prospect",Value = "Prospect"},
new SelectListItem{Text = "Reseller",Value = "Reseller"},
new SelectListItem{Text = "Supplier",Value = "Supplier"},
new SelectListItem{Text = "Vendor",Value = "Vendor"},
new SelectListItem{Text = "Other",Value = "Other"}
};
Account account = new Account
{
Name = "khaled",
Email = "test",
AccountType = listItems[accountType].Text
};
ViewBag.items = listItems;
return View(account);
}
My View: @using System.Globalization @model Form_Task.Models.Account
<div class="form-group">
@Html.Label("accounttype", "Account Type")
@Html.DropDownListFor(Model=>Model.AccountType,(List<SelectListItem>)ViewBag.items,new{@class = "form-control", @disabled="disabled"})
</div>
My Model:
public class Account
{
public string Name { get; set; }
public string Email { get; set; }
public string AccountType { get; set;}
}
If i change accountType
to string and create the model like the following, it works fine:
Account account = new Account
{
Name = "khaled",
Email = "test",
AccountType = accountType
};