2

I have the following code that generates a drop-down list with values:

@Html.DropDownListFor(m => Model.BeslutsinformationstypId, VardemangderHelper.BeslutsInformationsTyperForInteckningarGetList(), new { @class = "form-control")})

Now I want to a select option per default. I have tried the following:

@Html.DropDownListFor(m => Model.BeslutsinformationstypId, VardemangderHelper.BeslutsInformationsTyperForInteckningarGetList(), new { @class = "form-control", Selected = VardemangderHelper.BeslutsInformationsTyperForInteckningarGetList().First(x => x.Value == "320").Selected = true})

But that don't work. How can I set selected option based on the values from VardemangderHelper.BeslutsiinformationsTyperForInteckningarGetList()?

Is It possible to do this in Razor?

Bryan
  • 3,421
  • 8
  • 37
  • 77

1 Answers1

2

If you need to select an option by default when the view is rendered then you need to set the Model.BeslutsinformationstypId property before returning the view like below:

var model = // My model instantiation
// He set some properties if you want
model.BeslutsinformationstypId = 320;

return View(model);

If you can set it in your action, you can do it inside the view but I prefer to set it into controller action:

@{
     Model.BeslutsinformationstypId = 320
}

And your dropdown will still be the same line of code you wrote in your question :

@Html.DropDownListFor(m => Model.BeslutsinformationstypId, VardemangderHelper.BeslutsInformationsTyperForInteckningarGetList(), new { @class = "form-control")})
CodeNotFound
  • 22,153
  • 10
  • 68
  • 69