chrisblue13
chrisblue13

Reputation: 373

Default value Select List

I'm trying to set the default option of a Select List in MVC

I'm doing the following but it is not working

@Html.DropDownListFor(Model => Model.CandidateOrderLine.SiteId, new SelectList(Model.Customer.Sites, "SiteId", "SiteName", Model.Customer.Sites.Where(x => x.IsPrimarySite == true).ToString()), "Select Site", new { @class = "form-control", @data_val_required = "Please select a site" })

Any help with this would be appreciated,

thanks

Chris

Upvotes: 1

Views: 1416

Answers (2)

OMANSAK
OMANSAK

Reputation: 1332

Can you try it ? ...Model.Customer.Sites.Where(x => x.IsPrimarySite == true).FirstOrDefault().ToString())...

Upvotes: 1

Shyju
Shyju

Reputation: 218722

Assuming your GET action is setting a valid SiteId value to the Model.CandidateOrderLine.SiteId property

Just assuming your class names looks like these

public ActionResult Create()
{
   var vm=new YourVideModelClass();
   vm.CandidateOrderLine= new CandidateOrderLine();
   vm.SiteId = 3; // Hard coded for demo. Replace with valid SiteId
   return View(vm);
}

This should work.

@Html.DropDownListFor(Model => Model.CandidateOrderLine.SiteId, 
         new SelectList(Model.Customer.Sites, "SiteId", "SiteName")), 
         "Select Site",
          new { @class = "form-control", @data_val_required = "Please select a site" })

This will select the option with the value which is matching to what we set in our GET action.

Upvotes: 1

Related Questions