0

I have a drop down using

@Html.DropDownListFor(model => model.param, new SelectList
      (Model.MyList, "Value", "Text"), "Select")

This sets the first item of list to "select". I have two questions: Can I assign a class to this drop down as well as the selected value? I tried

 @Html.DropDownListFor(model => model.param, new SelectList
      (Model.MyList, "Value", "Text"), new{@class="clname", @value="Select")

but it does not work

Also, can I set a value to the default text select so that its value will not be an empty string?

1 Answer 1

1

I load my select lists in a controller. So it comes onto the page as part of the viewmodel.

The following will load the drop down with a css class clname and the first option will be "-- Select --"

@Html.DropDownListFor(model => model.param, 
          Model.MySelectList, 
          "-- Select --", 
          new { @class = "clname"})

Also, can I set a value to the default text select so that its value will not be an empty string?

For this, you should load the select list in the controller with the appropriate values.

ViewModel:

public class HomeViewModel
{
    public string MyParam {get;set;}
    public List<SelectListItem> MySelectList {get;set;}
}

Controller:

public class HomeController
{
    public ActionResult Index()
    {
          var model = new HomeViewModel();
          // to load the list, you could put a function in a repository or just load it in your viewmodel constructor if it remains the same.
          model.MySelectList = repository.LoadMyList();
          model.MyParam = "Select"; // This will be the selected item in the list.
          return View(model);
    }
}

View:

@model MyProject.HomeViewModel

<p>Select:
@Html.DropDownListFor(model => model.MyParam, 
          Model.MySelectList, 
          new { @class = "clname"})
</p>

Hope that makes it clear.

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

Comments

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.