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 class="editor-field">
  <td>@Html.AjaxComboBoxFor(model => model.CategoryId, "/Category/Lookup", "/Category/Caption")</td>
  <td>@Html.ValidationMessageFor(model => model.CategoryId)</td>

Controller's code:

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)

  return Json(
    cnt = FilteredCategory.Count()

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

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

    ,cnt_page = PagedFilter.Count()



public string Caption(string q_word)
 using (var svc = SessionFactoryBuilder.GetSessionFactory().OpenSession())
  if (string.IsNullOrEmpty(q_word))
   return "";
    .Where(x => x.CategoryId == int.Parse(q_word))
    .Select(x => x.CategoryName)


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