Chosen and Jquery and MVC
In the MVC forums I have seen a reference to Chosen. From the description here:
“Chosen is a JavaScript plugin that makes long, unwieldy select boxes much more user-friendly.”
It look beautifool – and I see the opportunity to improve my toolbox. I said: “I will do in 10 minutes”. Well, it did take longer – but not so long.
I will make an example my tutorial mvc and ajax – since it does not require any database.
So I download the source from https://github.com/harvesthq/chosen/ , put the .js in Scripts folder, the .css in Contents folder and registered in JqueryMVCRazor\JqueryMVCRazor_Web\Views\Shared\_Layout.cshtml
<link href="@Url.Content("~/Content/chosen.css")" rel="stylesheet" type="text/css" /> <script src="@Url.Content("~/Scripts/chosen.jquery.min.js")" type="text/javascript"></script>
Here is the code : ( from JqueryMVCRazor\JqueryMVCRazor_Web\Views\Shared\EditorTemplates\EditEmployeeViewModel.cshtml ):
@{ var idcombo = "#"+ ViewData.TemplateInfo.GetFullHtmlFieldId("cmbemp" + Model.Employee.IdEmployee); }<script> $(document).ready(function () { $("@idcombo").chosen({ no_results_text: "No results matched"}); }); </script>
And I said, this will be all.
Not so: see the picture – the names does not show up:
First I was thinking that it does not select the item. After several attempts, I realize the “…” ( three dots) – that means the width was not enough.
Next move, since I was in the javascript mood, was to add some javascript to adjust the width to fit:
So the code becomes:
$("@idcombo").chosen({ no_results_text: "No results matched" }); $("@idcombo").width("350");
No difference. So I tried the opposite way:
$("@idcombo").width("350"); $("@idcombo").chosen({ no_results_text: "No results matched" });
And , thinking about a bit, it is better right in the Dropdown declaration :
@Html.DropDownList("cmbemp" + Model.Employee.IdEmployee, new SelectList(Model.DepartmentList, "IDDepartment", "NameDepartment", Model.Employee.Department.IdDepartment),new{ style="width:350px;"})
Summary:
Integration of Chosen with MVC dropdown is rather simple. Add the .js, the .css, register in the page, add $(“@idcombo”).chosen() declaration and do not forget the width of the dropdown ( select )
Source code here
Later edit: Please add also
to the header