Monday, April 18, 2011

Added Html and Json attributes on ASP.NET MVC Helper for jQuery Ajax ComboBox

On view:

<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",
   new { style = "width: 300px " } // html attributes for span
   new { sub_info = true } ) // other json attributes for jQuery Ajax ComboBox 
  </td>
  <td>@Html.ValidationMessageFor(model => model.CategoryId)</td>
 </tr>
 </table>
</div>

On controller:

[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()

                // these are the sub info:
                ,attached = PagedFilter.Select(x =>                    
                        new[]
                        {
                            new string[] { "Code", x.CategoryCode } ,
                            new string[] { "Ranking", x.Ranking.ToString() }
                        }
                    )
            }
            );

    }//using
}//Lookup


[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();
    }

}


Working code available on: http://code.google.com/p/jquery-ajax-combobox-aspnet-mvc-helper/downloads/list

No comments:

Post a Comment