1

I'm displaying a dropdown list for countries, which is populated from a database call in the controller. On page load I would like the selected value to default to 'United States'. How do I do this?

Code from view:

<div class="form-group">
            @Html.LabelFor(m => m.Country)
            @Html.DropDownListFor(m => m.Country, new SelectList(Model.CountriesDDL, "CountryCode", "Country"), "--Select--", new { @class = "form-control" })
</div>
2
  • Possible duplicate of DropDownList how select default value Commented Jul 13, 2016 at 14:07
  • You have a few ways of going about this. You can always create the list in the controller and select a default item there. You can either put the list of SelectedListItems in your model or in a ViewBag. You can always use Jquery, and when the Window loads select an item based on your criteria. Commented Jul 13, 2016 at 14:23

1 Answer 1

1

In your GET action, you can set the value of Country property to the CountryCode of United states (or whatever country you want to set as default) of your view model

public ActionResult Show()
{
  var vm = new YourViewModel();
  vm.CountriesDDL = GetCountriesFromSomeWhere();
  vm.Country="United States";
  return View(vm);
}

Assuming Country is of type string

Sign up to request clarification or add additional context in comments.

2 Comments

Let's say the dropdown list is on a form submission page. What happens if a user were to select "Canada" from the drop down list and submit the form, but the form is invalid. Would the dropdown list still show "Canada" or would it default back to "United States"?
When you change to Canada, the Country will be updated to Canada in the HttpPost when it receives the form data.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.