Friday, April 15, 2011

ASP.NET MVC Helper for jQuery Ajax ComboBox

View's code:

<div class="editor-label">
 @Html.LabelFor(model => model.CategoryId, "Category")
</div>
<div class="editor-field">
 <table>
 <tr>                    
  <td>@Html.AjaxComboBoxFor(model => model.CategoryId, "/Category/Lookup", "/Category/Caption")</td>
  <td>@Html.ValidationMessageFor(model => model.CategoryId)</td>
 </tr>
 </table>
</div>

Controller's code:

[HttpPost]
public JsonResult Lookup(string q_word, string primary_key, int per_page, int page_num)
{


 using (var svc = SessionFactoryBuilder.GetSessionFactory().OpenSession())
 {

  var FilteredCategory = svc.Query<Category>()
        .Where(x => q_word == "" || x.CategoryName.Contains(q_word));


  var PagedFilter = FilteredCategory.OrderBy(x => x.CategoryName)
        .LimitAndOffset(per_page, page_num)
        .ToList();

  return Json(
   new
   {
    cnt = FilteredCategory.Count()

    ,primary_key = PagedFilter.Select(x => x.CategoryId)

    ,candidate = PagedFilter.Select(x => x.CategoryName)

    ,cnt_page = PagedFilter.Count()

   }
   );

 }//using
}//List


[HttpPost]
public string Caption(string q_word)
{
 using (var svc = SessionFactoryBuilder.GetSessionFactory().OpenSession())
 {
  if (string.IsNullOrEmpty(q_word))
   return "";
  else
   return 
    svc.Query<Category>()
    .Where(x => x.CategoryId == int.Parse(q_word))
    .Select(x => x.CategoryName)
    .SingleOrDefault();
 }

}

Please do note that I modify the jQuery Ajax ComboBox's code a bit, so as to make the combobox's emitted name be compatible to ASP.NET MVC's Model

Get the code from SVN !

Or download it from google code

No comments:

Post a Comment