c# - mvc dropdown not showing selected index -
i have following on controller:
string preferredlanguage = "fr-ca"; viewdata["languages"] = new selectlist(languages, "code", "name", preferredlanguage);
on view:
@html.dropdownlist("languages", (selectlist)viewdata["languages"], new { id = "languages" });
my problem here dropdown not setting selected index of dropdown preferred language supposed french.
note:
the values inside languages
:
1) name = "english" code = "en-us" 2) name = "french" code = "fr-ca"
and dropdown shows 2 languages, english , french. english set selected index want french.
the reason show languages
way because object being retrieved database method , not hardcoded. in advance!
i'd recommend using strongly-typed helpers bound model; along these lines:
model:
public class languageformmodel { public string selectedlanguage { get; set; } public selectlist languages { get; set; } }
action:
[httpget] public actionresult youractionname() { // replace you're getting language variable var languages = new collectionofsomesort(); var model = new languageformmodel() { selectedlanguage = "fr-ca", languages = new selectlist(languages, "code", "name", "fr-ca") }; return view(model); }
view:
@model your.fully.qualified.namespace.languageformmodel @html.labelfor(m => m.selectedlanguage) @html.dropdownlistfor(m => m.selectedlanguage, model.languages, "select one...")
i'm not huge fan of using viewdata
other simple messages, , use tempdata
, since i'm showing confirmations/alerts.
Comments
Post a Comment