this is what i am doing for drop down list
controller code
public ActionResult Contact()
{
Contact homeViewModel = new Contact();
homeViewModel.subject = new List<Subject>();
homeViewModel.subject.Add(new Subject { Id = 1, subject1 = "General Customer Service" });
homeViewModel.subject.Add(new Subject { Id = 2, subject1 = "Suggestions" });
homeViewModel.subject.Add(new Subject { Id = 3, subject1 = "Product Support" });
homeViewModel.Selectedid = 1; //this sets the default value for your dropdown
return View(homeViewModel);
}
Model code :
public class Contact
{ [Required(ErrorMessage="Please fill the following")]
public string name { get; set; }
[Required(ErrorMessage = "Please Enter Correct Username")]
[RegularExpression(@"^([0-9a-zA-Z]([\+\-_\.][0-9a-zA-Z]+)*)+@(([0-9a-zA-Z][-\w]*[0-9a-zA-Z]*\.)+[a-zA-Z0-9]{2,3})$", ErrorMessage = "Please provide valid email id")]
public string email { get; set; }
public List<Subject> subject { get; set; }
[Required(ErrorMessage="Please fill the following")]
public string message { get; set; }
public int Selectedid { get; set; }
}
View Code :
@Html.DropDownList("Selectedid", new SelectList(Model.subject, "Id", "subject1", Model.Selectedid), new { @class = "form-control", id = "subject", required = "required" })
SlpCodein the controller before you pass the model to the view. If it matches one of the option values (theValueproperty ofSalesEmployee1) then that option will be selectedViewModel.SlpCode = "DefaultValue"to set DDList default value before returning view in your controllerGETmethod, assume you have a viewmodel.