Elisabeth
Elisabeth

Reputation: 21206

First item in DropDownListFor control should not be selected initially

My OpenTestplanListViewModel has a DisplayList with 3 items bound to the DropDownList.

When the user selects explicitly no item in the DropDownList always the first is automatically selected.

Using a ListBoxFor instead a DropDownListFor I have not this problem. Is it somehow possible to tell the DropDownListFor "Do not select any item initially!" ?

@model ITMS.Web.Models.OpenTestplanListViewModel

@{
    Layout = null;   
} 

@using (Html.BeginForm("Open", "Testplan"))
{ 
    @Html.ValidationSummary(false)      
    @Html.DropDownListFor(x => x.TestplanIdAndTemplateId, new SelectList(Model.DisplayList, "TestplanIdAndTemplateId", "Name"), new { @class = "listviewmodel" })  
}

public class OpenTestplanListViewModel
{
    [Required(ErrorMessage = "No item selected.")]
    public string TestplanIdAndTemplateId { get; set; } 
    public IEnumerable<OpenTestplanViewModel> DisplayList { get; set; }

    public int? SelectedTestplanId
    {
        get
        {
            return !String.IsNullOrEmpty(TestplanIdAndTemplateId) ? Convert.ToInt32(TestplanIdAndTemplateId.Split(new[] { '_' }).First()) : (int?)null;
        }
    }
    public int? SelectedTemplateId
    {
        get
        {
            return !String.IsNullOrEmpty(TestplanIdAndTemplateId) ? Convert.ToInt32(TestplanIdAndTemplateId.Split(new[] { '_' }).Last()) : (int?)null;
        }
    }
}

Upvotes: 1

Views: 8059

Answers (2)

Nate-Wilkins
Nate-Wilkins

Reputation: 5492

@Html.DropDownListFor(x => x.TestplanIdAndTemplateId,
    new SelectList(Model.DisplayList, "TestplanIdAndTemplateId", "Name"),
    "-- Select Item --",
    new { @class = "listviewmodel" }) 

The question @Display Name posted is very similar just took a look at it. If you want to know more about how the model or the controller works take a look at it here: Problem with DropDownListFor SelectedItem

The Method DropDownListFor of the SelectExtensions class is overloaded. With 8 different methods check out http://msdn.microsoft.com/en-us/library/system.web.mvc.html.selectextensions(v=vs.108).aspx for more information about what each takes and does.

Upvotes: 0

Display Name
Display Name

Reputation: 4732

Look into Problem with DropDownListFor SelectedItem. I think if I understood your question correctly, they solved the problem you're having.

Hope this helps.

Upvotes: 2

Related Questions