asp.net mvc - Cannot get Dropdownlist to work properly -
i want simple dropdownlist contains values "ascending" , "descending" sent controller sortorder when search button pressed in index() method. have tried many different things , cannot work, doing wrong.
p.s not want make model, want simple "asc" or "desc" dropdown sortorder variable.
usercontroller.cs
public viewresult index( string searchstring, string sortorder = "asc") { var sortorderparam = new[] { new selectlistitem { value = "asc", text = "ascending" }, new selectlistitem { value = "desc", text = "descending" } }; var users = u in db.tbl_sys_user select u; if (!string.isnullorempty(searchstring)) { users = users.where(x => x.user_first_name.toupper().contains(searchstring.toupper())); } switch (sortorder) { case "desc": users = users.orderbydescending(u => u.user_first_name); break; default: users = users.orderby(u => u.user_first_name); break; } populatefielddropdownlist(""); return view(users.tolist()); }
index.cshtml
@using (html.beginform()) { <p> search criteria: @html.textbox("searchstring") order by: @html.dropdownlist("sortorderparam") <input type="submit" value="search"/> </p> }
in controller action, should create list of dropdownlist options , pass them view in viewbag, or property of viewmodel. below:
public viewresult index(string searchstring, string sortorder = "asc") { var users = u in db.tbl_sys_user select u; if (!string.isnullorempty(searchstring)) { users = users.where(x => x.user_first_name.toupper().contains(searchstring.toupper())); } switch (sortorder) { case "desc": users = users.orderbydescending(u => u.user_first_name); break; default: users = users.orderby(u => u.user_first_name); break; } populatefielddropdownlist(""); var sortorderoptions = new list<selectlistitem>(); sortorderoptions.add(new selectlistitem { value = "asc", text = "ascending" }); sortorderoptions.add(new selectlistitem { value = "desc", text = "descending" }); viewbag.sortorderoptions = sortorderoptions; return view(users.tolist()); }
the first argument in html.dropdownlist
method name of field (which name of value posted action), , second 1 ienumerable<selectlistitem>
options in dropdownlist. so, view this:
@using (html.beginform()) { <p> search criteria: @html.textbox("searchstring") order by: @html.dropdownlist("sortorderparam", viewbag.sortorderoptions) <input type="submit" value="search"/> </p> }
Comments
Post a Comment