Tuesday, October 30, 2012

Display combo with grid using MVC and JQuery.

Introduction :

In most of web application, we have requirement to choose one option from the multiple list at that time we provide combo box to the end user to choose one option. But it will okay when value display into combo box is unique.

But if there is case when display one value is not enough for user to choose right option for this, there is need to give UI like grid, using this user will easily identify which option is right one.

Before few days, I came across very good Jquery pluginfor display Grid in Combo box. At that time, I think this one is great UI to solve above problem. so in this article we will show how to display grid in combo box using jquery easy ui plugin with asp.net mvc.

Implementation :

To implement this, you need download file from Jquery EasyUI.

Now, create new blank mvc application in visual studio and add following files into script folder from the downloaded zip files.

  • jquery-1.7.1.min.js
  • jquery.easyui.min.js

Add following folders/files into content folder of mvc application from the downloaded zip files.

  • easyui.css
  • icon.css
  • images folder
  • Icons folder

After adding files/folders into relevant folders, add one controller named combogrid and also add one action method for this also. Controller code of will look like below.

public class combogridController : Controller
{ 
  Public ActionResult Index()
  {
     Return view();
  }
}

Now, Create new view with name index.cshtml in combogrid Folder and Add reference of .js and .css files which mention above.

    <link href="@Url.Content("~/Content/JQueryEasyUI/demo.css")" rel="stylesheet"/>
    <link href="@Url.Content("~/Content/JQueryEasyUI/easyui.css")" rel="stylesheet"/>
    <link href="@Url.Content("~/Content/JQueryEasyUI/icon.css")" rel="stylesheet"/>
    <script src="@Url.Content("~/Scripts/jquery-1.7.1.min.js")"></script>
    <script src="@Url.Content("~/Scripts/jquery.easyui.min.js")"></script>

Now I have taken example of the students data display into combo grid. For this, I have created one model class named Students. Model class will looks like a below.

public class Students
{
    public int StudentID;
    public string StudentName;
    public string Address;
    public string City;
}

After that, In View I have placed following html

<h2>ComboBox Plugins  Using JQuery Easy UI.</h2>
<hr />
 <h3>Combo Grid Plugin</h3>   
<select id="drpSelectStudents" name="Students" style="width:290px;"></select>

Now, to display combo with grid, need to write following JavaScript code in view.

<script>
      $(function(){
      $('#drpSelectStudents').combogrid
                     ({
    panelWidth:290,
    value:'006',
                                idField: 'StudentID',
    textField: 'StudentName',
    url: '/combogrid/GetStudentsInfo',
    columns:[[
     { field: 'StudentName', title: 'StudentName', width: 60 },
     { field: 'Address', title: 'Address', width: 100 },
     { field: 'City', title: 'City', width: 120 }
           ]]
    });
          });
  
</script>

Now, in combo grid function I have define StudentId as id field and StudentName as TextField.In url field, need to define controller action which will return json for the datasource of the grid.

To display column in grid, we need to define column field with its field name, title and width parameter.

After define this javascript block, we are define action in controller named GetStudentsInfo which will return Json of Students info.

 public JsonResult GetStudentsInfo()
 {
            List lstStudents = new List();
            lstStudents.Add(new Students { StudentID = 1, StudentName = "ABC", Address = "Main Road", City ="City1"});
            lstStudents.Add(new Students { StudentID = 2, StudentName = "DEF", Address = "Main Road", City = "City2" });
            lstStudents.Add(new Students { StudentID = 3, StudentName = "GHI", Address = "Main Road", City = "City3" });
            lstStudents.Add(new Students { StudentID = 4, StudentName = "JKL", Address = "Main Road", City = "City4" });

            return Json(lstStudents, JsonRequestBehavior.AllowGet);
}

Now run the application,and click on combo you will get combo with grid. Now, Question arise how to get, set and reload values of the combo for this I have added 3 buttons in Views.

<input type="button" value="Get Selected Value" onclick="GetSelectedValue()" />
<input type="button" value="Set Selected Value" onclick="SetSelectedValue()" />
<input type="button" value="Reload" onclick="ReloadValue()" />

And also write following JavaScript in views.

  function ReloadValue() 
  {
           $('#drpSelectStudents').combogrid('grid').datagrid('reload');
  }
  function SetSelectedValue()
  {
    $('#drpSelectStudents').combogrid('setValue', '2');
  }
  function GetSelectedValue() 
  {
    var val = $('#drpSelectStudents').combogrid('getValue');
    alert(val);
  }

Now, again run the application and click on selected value button, in your combo value is set to 2 (because in set value function we are defining value as 2:).).To get value click on the get value button it will display alert with value and to reload value of grid click on reload button.

Conclusion:

I’ve been using this plugin just wants to show you that we can provide more user friendly combo. Hopefully, you'll find this as useful as I have found it for my code.

Sunday, October 7, 2012

Under the hood of @Html.Checkbox()

Yesterday, I have used checkbox helper in my mvc project and found some interesting thing when I saw render html of checkbox helper and access value of checkbox from form collection in controller action. I have described both the things below.

1. CheckBox helper renders 2 input element :-

The CheckBox helper is different from the other controls because it will render two input elements. I have tried with following code in a view.

@Html.Checkbox(‘chkAcceptPolicy’)

And check this code in browser source view it will render following html.



I have probably wondering why the helper renders a hidden input in addition to checkbox input. After thinking over that I have found reason for that the HTML Specification indicates that a browser will submit a value for a checkbox only when checkbox is checked. So as per above example that if chkAcceptPolicy checkbox value is not checked then second input guarantees a value will appear.

2. Form Collection returns value of both input element :-

If we are used model binding approach then it will return value true if value of checkbox is checked otherwise return false.

But here, I have tried to access checkbox value from the Form Collection or Request Object.

        [HttpPost]
        public ActionResult Index(FormCollection fB)
        {
            ViewBag.ValueofCheckBox = fB["chkAccpetPolicy"];
            return View();
        }

Here I am found some interesting thing. If you are checked value of checkbox at that time you are getting value of checkbox from the form collection object as “true,false”.

Why it will contains both value because as per HTML Specifications that a browser will submit a value with comma separated when both element have name same.

So here, chkAcceptPolicy checkbox value is checked and hidden element value is false ndue to this formcollection return value a ‘true,false’.

The goal of this article just show you unique thing about @html.checkbox.Hope this will help you.