GeekyNuns GeekyNuns - 2 months ago 7
ASP.NET (C#) Question

DropDownList selected is not set

I have a view where i use DropDownListFor:

@Html.DropDownListFor(m => m.Nationality, NationalityDD, new { style = "width:185px;" })


SelectListItem List is reneged following way :

List<SelectListItem> NationalityDD = new List<SelectListItem>();
var n0 = new SelectListItem { Value = "", Text = "" };
var n1 = new SelectListItem { Value = "p", Text = @Resources.Localization.nationality_LR_citizen };
var n2 = new SelectListItem { Value = "np", Text = @Resources.Localization.nationality_LR_resident };
var n3 = new SelectListItem { Value = "es", Text = @Resources.Localization.nationality_ES_citizen };
var n4 = new SelectListItem { Value = "ne", Text = @Resources.Localization.nationality_other };

NationalityDD.Add(n0); NationalityDD.Add(n1); NationalityDD.Add(n2); NationalityDD.Add(n3); NationalityDD.Add(n4);


So, the issue is that when I set np/es/ne values into database, after refreshing page everything is fine and selected values are still shown, but if I set
p
after page is refreshed there is no selected value "".

This html is generated by DDL when I choose
p
(after refresh):

<select id="Nationality" name="Nationality" style="width:185px;">
<option value=""></option>
<option value="p">LR pilsonis</option>
<option value="np">LR Pastāvīgais iedzīvotājs</option>
<option value="es">ES pilsonis</option>
<option value="ne">ne-ES pilsonis</option>
</select>


and when I select something except
p
(after refresh):

<select id="Nationality" name="Nationality" style="width:185px;"><option value=""></option>
<option value="p">LR pilsonis</option>
<option value="np">LR Pastāvīgais iedzīvotājs</option>
<option selected="selected" value="es">ES pilsonis</option>
<option value="ne">ne-ES pilsonis</option>
</select>


What could be the reason of such a strange behavior of DDL?

Answer

Mistake was too stupid.. In database I am using the Nationality field was created not nvarchar(2), but simple char(2), so in case of nationality_LR_citizen = p it was space left, so the p== p was false and DDLF did not select this value.

Comments