Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC Razor: Add empty value to a DropDownList

I tried for hours to get it work, but now I have to ask..

As read in
/942262/add-empty-value-to-a-dropdownlist-in-asp-net-mvc and /3780614/mvc-clear-default-selected-value-of-selectlist
I want to add an empty space to dropdown lists in my ASP.NET MVC Razor WebApp with Entity Framework 5 to force the user for an input.

I followed the informations, but what happend in the View is that: http://i.stack.imgur.com/EXSgT.png
So, as you see, there is an empty space, but it isn't selected by default. Instead, my "testproject", as first value from my controller, is marked.. Not the empty space. So where did I fail?

Thanks a lot.

My model looks like that:

    [...]
    using System.Web.Mvc;

    public class UploadTranferContainer
    {    
         [DisplayName("Project")]
         public int ProjectID { get; set; }

         public SelectList Projects { get; set; }
    }

My controller fills the data in like:

    UploadTranferContainer container = new UploadTranferContainer();
    container.Projects = new SelectList(db.Projects.AsEnumerable(), "ProjectID", "ProjectName");

And the view unpacks my container like:

        <div class="editor-label metadataLabel">
            @Html.LabelFor(x => x.ProjectID)
        </div>
        <div class="editor-field">
            @Html.DropDownListFor(x => x.ProjectID, Model.Projects, string.Empty)
        </div>            
like image 455
Mexx_ Avatar asked Dec 03 '13 20:12

Mexx_


People also ask

How to populate DropDownList in mvc?

In this article, I have shown you simple ways to populate a dropdown, like directly by hardcoding in the view, using viewdata, viewbag and Ajax. An Index is a default action created when you add a controller. Add a view page for this index action by right-clicking on Index and add View (Index).


2 Answers

you can use below approach for dropdown with empty values

@Html.DropDownListFor(x => x.ProjectID, new SelectList(Model.Projects, "ProjectID", "ProjectName"), " ")
like image 56
Rajshee Turakhia Avatar answered Oct 17 '22 19:10

Rajshee Turakhia


The selected value of the dropdown will be the value (if found) of Model.ProjectID

If you want this to appear as the first (empty) option of the select, make sure the value of ProjectID is not contained in the select list items Model.Projects

like image 40
Jay Avatar answered Oct 17 '22 17:10

Jay