Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert initial blank row into select list MVC LINQ SQL

Tags:

I have the following code that is in my formViewModel to be passed to my View.

        var ownerValues = aspnet_Users             .OrderBy(u => u.Surname)             .Select(u => new KeyValuePair<int, string>(u.UserId, u.Surname + " " + u.Forename.ToString() + " [" + u.UserName.ToString() + "]"));         this.OwnersList = new SelectList(ownerValues, "Key", "Value", incidentAction.OwnerId); 

When I run the view in explorer my drop list defaults to the first item and I want it to default to a blank row.

So my plan is to insert a initial row with userId = null and then an empty string instead of 'please select' or something similar.

Can anyone please advise me on how to do this on one line of code I think, not sure where to start.

thanks

like image 553
John Avatar asked Jun 23 '11 03:06

John


1 Answers

When Rendering your SelectList you can do something like

<%:Html.DropDownListFor(x => x.ApprovalType, Model.ApprovalTypes,"")%> 

if you want strongly typed list or you can try

<%:Html.DropDownList("ApprovalType", Model.ApprovalTypes, "") %> 

in both examples Model.ApprovalTypes contains a SelectList or List of SelectListItems. Empty string parameter at the end is optional label and its value is also an empty string
Edit Inserting label (empty string or something else) with some value will also create problems when you try to validate it using data annotations. Selecting empty label will not trigger the error message because associate value will be -1 (not empty) as suggested in other answer.

like image 64
Muhammad Adeel Zahid Avatar answered Sep 27 '22 18:09

Muhammad Adeel Zahid