0
ViewBag.UserStatusList = new List<SelectListItem>
{
    new SelectListItem{Text = "Active", Value = "1",Selected=true},
    new SelectListItem { Text = "Inactive", Value = "0",Selected=false }
};

the above shows the viewbag which i am binding to dropdown list . So here I want to fix Active as default item in the view page. How can I do that please give some suggestions

@Html.DropDownListFor(m => m.UserStatus, (IEnumerable<SelectListItem>)ViewBag.UserStatusList, new { @id = "ddlCustomerStatusList", @class = "form-control", @selected = "selected" })

This is my view

Binoy Kumar
  • 422
  • 3
  • 17
  • Show your view (setting the `Selected` property of `SelectListItem` is pointless if your correctly binding to a model property) –  Sep 26 '16 at 05:53

1 Answers1

1

You need to set the value of your model property in the GET method before you return the view

model.UserStatus = 1;
return View(model);

You can delete setting the Selected property of SelectListItem because its ignored by the DropDownListFor() method (internally the method builds a new IEnumerable<SelectListItem> based on the value of the property your binding to)

Note also you should delete new { @selected = "selected" }(that is not a valid attribute for a <select> element) and there is no need to use new { @id = "ddlCustomerStatusList" } as the helper already creates an id attribute (its id="UserStatus")

  • Thanks for your reply I did the changes but still i am getting inactive as default item , is there anything else which I am missing.? Consider me as a beginner – Binoy Kumar Sep 26 '16 at 06:11
  • It is working when i put model.UserStatus=1 before my viewbag. Thanks a lot – Binoy Kumar Sep 26 '16 at 06:21
  • You should not be using `ViewBag`. You should be using a [view model](http://stackoverflow.com/questions/11064316/what-is-viewmodel-in-mvc) with a property for the `SelectList` so its strongly typed (refer [this question/answer](http://stackoverflow.com/questions/34366305/the-viewdata-item-that-has-the-key-xxx-is-of-type-system-int32-but-must-be-o)) –  Sep 26 '16 at 06:22