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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With