How can I set default value in Selected List in MVC?

I am working on NopCommerce customization. I am using one selected list. And I want to make one value called Active is as default. My code is as below -

foreach (StatusEnum item in Enum.GetValues(typeof(StatusEnum)))
            {   
                newCycleModel.AvailableStatuses.Add(new SelectListItem()
                {
                    Text = item.ToString(),
                    Value = ((int)item).ToString(),
                });
            }
            test.AvailableStatuses.Insert(0, new SelectListItem() { Text = 'All', Value = "0" });

In StatusEnum i have two status as 'Active' and 'Close'

I want to put Active as default. How can I achieve this?

Answers


You could just set the Selected property based on the current item:

newCycleModel.AvailableStatuses.Add(new SelectListItem()
{
    Text = item.ToString(),
    Value = ((int)item).ToString(),
    Selected = (item == StatusEnum.Active)
}

This should result in the select item being selected if you use in the View:

@Html.DropDownList("myddlist", Model.AvailableStatuses)

Need Your Help

Git unable to create file permission denied

linux git ubuntu

I am using Amazon EC2 to host a website which is deployed to the server via git. I used this tutorial previously on the same kind of EC2 Ubuntu Linux Server instance, and it has worked flawlessly.