Thursday, July 31, 2014

Integration of jqGrid With MVC4 Application: Part 2

Integration of jqGrid With MVC4 Application: Part 2

 

jqGrid

 

Actually I needed to implement it in my project and I encountered many difficulties in getting this feature because I hardly found any help for it and if I found something then it was just halfway useful.
I recommend you to visit this before proceeding with this article.

This is a second part of Integration of jqGrid with MVC4 application. This part is more about enabling add, edit, delete and refresh as well as a little validation using builtin validation keywords.

  • Enabling jqGrid add, edit, delete and refresh
  • Validation keywords

To learn more about MVC kindly go to C# Corner MVC Section or My Blog.
I've developed this sample application using Visual Studio 2012 and used Entity Framework to retrieve information from the database.

Step 1 : Enabling jqGrid add, edit, delete and refresh



After enabling values we should run the application and press F5. Kindly see the following image.


I have pasted this URL into a browser http://localhost:26158/Admin to get the above result.
Here is the complete code of AddTopic.cshtml, though I will share the AdminController class file and AddTopic.cshtml file with you as a sample so that you could add it into your solution.
Note: the code segment of jqGrid in the AddTopic.cshtml view is as shown below:

  1: @{  
  2: ViewBag.Title = "ADDTOPICS";  
  3: Layout = "~/Views/Shared/_Layout.cshtml";  
  4: }  
  5: <!DOCTYPE html>
  6: <html>
  7: <head>
  8: <meta name="viewport" content="width=device-width" />
  9: <title>AddTopics</title>
 10: <script src="~/Scripts/jquery.jqGrid.js"></script>
 11: <script src="~/Scripts/jquery.jqGrid.min.js"></script>
 12: <script src="~/Scripts/i18n/grid.locale-en.js"></script>
 13: <link href="~/Content/jquery.jqGrid/ui.jqgrid.css" rel="stylesheet" />
 14: <link href="~/Content/themes/base/jquery-ui.css" rel="stylesheet" />
 15: <!-- The jqGrid client-side javascript -->
 16:     @*   <script type="text/javascript" src="http://www.trirand.net/aspnetmvc/Scripts/trirand/jquery.jqGrid.min.js"></script>*@  
 17: <script type="text/javascript">
 18:         var ClickEventId;  
 19:         $(document).ready(function myfunction() {  
 20:             $('#list').jqGrid({  
 21:                 caption: "Add Topics",  
 22:                 url: '/Admin/GetTopics/',  
 23:                 datatype: "json",  
 24:                 contentType: "application/json; charset-utf-8",  
 25:                 mtype: 'GET',  
 26:                 colNames: ['ID', 'Name', 'Created_by', 'Created_On'],  
 27:                 colModel: [  
 28:                                 { name: 'ID', index: 'ID', width: 150, editable: true, editoptions: { readonly: 'readonly' }, editrules: { readonly: true } },  
 29:                                 {  
 30:                                     name: 'topic_name', index: 'topic_name', width: 150, editable: true, editrules: { required: true }  
 31:                                 },  
 32:                                 {  
 33:                                     name: 'Created_by', index: 'Created_by', width: 150, editable: true, editrules: { required: true }  
 34:                                 },  
 35:                                 { name: 'Created_On', index: 'Created_On', width: 150, editable: true, editrules: { required: true } }  
 36:                 ],  
 37:                 rowNum: 10,  
 38:                 loadonce: true,  
 39:                 pager: '#pager',  
 40:                 editurl: '/Admin/EditTopics/'  
 41: 
 42:             });  
 43: 
 44:             jQuery("#list").jqGrid('navGrid', '#pager', {  
 45:                 edit: true,  
 46:                 add: true,  
 47:                 del: true,  
 48:                 search: true,  
 49:                 refresh: true,  
 50:                 searchtext: "Search",  
 51:                 addtext: "Add",  
 52:                 edittext: "Edit",  
 53:                 deltext: "Delete",  
 54:                 refreshtext:"Refresh"  
 55:             }            
 56:        );  
 57:             $('.ui-pg-button').on('click', function (ev) {  
 58: 
 59: ClickEventId = this.id;  
 60:             });  
 61:         });  
 62: </script>
 63: </head>
 64: <body>
 65: <table id="list"></table>
 66: <div id="pager"></div>
 67:     @*<div>
 68: <%= Html.Trirand().JQGrid("", "EditDialogGrid") %>
 69: </div>*@  
 70: </body>
 71: </html>
 72: 

Code for AdminController: After putting this URL http://localhost:26158/Admin into a browser, it calls the Index Action that returns the AddTopics View and does other operations.

 

  1: using System;  
  2: using System.Collections.Generic;  
  3: using System.Collections.Specialized;  
  4: using System.Linq;  
  5: using System.Web;  
  6: using System.Web.Mvc;  
  7: using QuickBook.Models;  
  8: 
  9: namespace QuickBook.Controllers  
 10: {  
 11:     public class AdminController : Controller  
 12:     {          
 13:         // GET: /Admin/  
 14:         EmployeeEntities edb = new EmployeeEntities();  
 15:         public ActionResult Index()  
 16:         {  
 17:             return View("AddTopics");  
 18:         }  
 19: 
 20:         [HttpGet]  
 21:         public JsonResult GetTopics()  
 22:         {  
 23:             EmployeeEntities edb = new EmployeeEntities();  
 24:             var jsonData = new
 25:             {  
 26: total = 1,  
 27: page = 1,  
 28: records = edb.tblAddTopics.ToList().Count,  
 29: rows = (  
 30:                   from emp in edb.tblAddTopics.ToList()  
 31:                   select new  
 32:                   {  
 33: id = emp.id,  
 34: cell = new string[] {   
 35:                       emp.id.ToString(), emp.topic_name.ToString(), emp.created_by.ToString(),emp.created_on.ToString()   
 36:                       }  
 37:                   }).ToArray()  
 38:             };  
 39:             return Json(jsonData, JsonRequestBehavior.AllowGet);  
 40:         }  
 41:         [HttpPost]  
 42:         public void EditTopics(tblAddTopic postData, string ClickEventId)  
 43:         {  
 44:            // EmployeeEntities edb = new EmployeeEntities();  
 45:             if (ClickEventId == "edit_list")  
 46:             {  
 47:                 var editRecord =  
 48: edb.tblAddTopics.Where(x => x.id == postData.id).SingleOrDefault();  
 49: editRecord.topic_name = postData.topic_name;  
 50: editRecord.created_by = postData.created_by;  
 51: editRecord.created_on = postData.created_on;  
 52: 
 53:                 edb.SaveChanges();  
 54:             }  
 55:             else if (ClickEventId == null && postData.topic_name!=null)  
 56:             {  
 57:                 //var editRecord =  
 58:                 //  edb.tblAddTopics.Where(x => x.id == postData.id).SingleOrDefault();  
 59:                 //editRecord.topic_name = postData.topic_name;  
 60:                 //editRecord.created_by = postData.created_by;  
 61:                 //editRecord.created_on = postData.created_on;  
 62: 
 63:                 edb.tblAddTopics.Add(postData);  
 64:                 edb.SaveChanges();  
 65:             }  
 66:             else if (postData.topic_name==null)  
 67:             {  
 68:                 var DeleteRecord =  
 69: edb.tblAddTopics.Where(x => x.id == postData.id).SingleOrDefault();  
 70:                 edb.tblAddTopics.Remove(DeleteRecord);  
 71:                 edb.SaveChanges();  
 72:             }  
 73:         }  
 74:         [HttpGet]  
 75:         public JsonResult GetQuestionNo()  
 76:         {  
 77:             EmployeeEntities objEmpRegistration = new EmployeeEntities();  
 78:             List<Question> Questions = new List<Question>();  
 79: 
 80: Questions = (from p in objEmpRegistration.tblAddQuestions.ToList()  
 81:                          group p by p.category_id into g  
 82:                          select new Question  
 83:                          {  
 84: QuestionNO = g.Count() + 1,  
 85: categoryID = g.Key  
 86:                          }).ToList();  
 87: 
 88:             return Json(Questions,JsonRequestBehavior.AllowGet);  
 89:         }  
 90:         public ActionResult AddQuestion()  
 91:         {  
 92: 
 93:             return View(new UpdateCategory());  
 94:         }  
 95:         [HttpPost]  
 96:         public void Savequestion(int dropdownid, string Ques,string Ans)  
 97:         {  
 98:             tblAddQuestion addobj = new tblAddQuestion();  
 99: 
100: addobj.category_id = dropdownid;  
101: addobj.question = Ques;  
102: addobj.answer = Ans;  
103: addobj.created_by = 100;  
104: addobj.created_on = System.DateTime.Now;  
105:             edb.tblAddQuestions.Add(addobj);  
106:             edb.SaveChanges();  
107:           //  return ("successfully");  
108:         }  
109:     }  
110: }  

 


 


Validation keywords:



Kindly refer to the following image to understand grid-level validation.


Note: You can control more textual information at the grid.locale-en.js level, like caption, Add caption, the Submit button text and much more as shown in the image below.





I have added AddTopics.cshtml and Admincontroller.cs as a sample though I have already shared a database backup file in Part 1.You can download code from the link shown below:


http://www.c-sharpcorner.com/UploadFile/97fc7a/integration-of-jqgrid-with-mvc4-application-part-2/


Thanks.
Stay happy and stay codingSmile

Saturday, July 26, 2014

Integration of jqGrid with MVC4 application : Part1

Integration of jqGrid with MVC4 application

 

mvc4

 

This article is more about integration of JQGrid in MVC 4 application .Actually I needed to implement it in my project and I found lot of difficulties to achieve its feature because I hardly found its help and if I got that was half note.

I have divided this article in parts. This part is more about integration of jqGrid with MVC 4 application.in this article we will learn given below topics

  • Adding jqGrid reference file
  • Structure of jqGrid in View
  • Calling Controller’s action to bind result set with jqGrid
  • Return Json result from action in special format from DBContext

To know more about MVC kindly go through with the links given below:

I’ve developed this sample application into VS 2012 and used entity framework to retrieve information from Database. This is the basic layout of mvc application as depicted below having jqGrid libraries:

v Step1: Adding jqGrid reference file

clip_image002[4]

Step2: Structure of jqGrid in View

This is structure I have used as shown in image depicted below:

  1:   1:     <script src="~/Scripts/jquery.jqGrid.min.js"></script>
  2:   2:     <script src="~/Scripts/i18n/grid.locale-en.js"></script>
  3:   3:     <link href="~/Content/jquery.jqGrid/ui.jqgrid.css" rel="stylesheet" />
  4:   4:     <link href="~/Content/themes/base/jquery-ui.css" rel="stylesheet" />
  5:   5: 
  6:   6:     <script type="text/javascript">
  7:   7: 
  8:   8:         $(document).ready(function myfunction() {
  9:   9:            
 10:  10:             $('#list').jqGrid({
 11:  11:                 caption: "Employee Details",
 12:  12:                 url: '/Interview/GetEmployee/',
 13:  13:                 datatype: "json",
 14:  14:                 contentType: "application/json; charset-utf-8",
 15:  15:                 mtype: 'GET',
 16:  16:                 colNames: ['Address', 'City', 'Id', 'Name'],
 17:  17:                 colModel: [
 18:  18:                                 { name: 'Address', index: 'Address', width: 150 },
 19:  19:                                 { name: 'City', index: 'City', width: 150 },
 20:  20:                                 { name: 'Id', index: 'Id', width: 150 },
 21:  21:                                 { name: 'Name', index: 'Name', width: 150 }
 22:  22:                 ],
 23:  23:                 rowNum: 10,
 24:  24:                 loadonce: true
 25:  25: 
 26:  26:             });
 27:  27: 
 28:  28:             jQuery("#list").jqGrid('navGrid', '#pager', { edit: true, add: true, del: true });
 29:  29:         });
 30:  30:  </script>
 31: 

Step3: Calling Controller’s action to bind result set with jqGrid

In this step we will call controller’s action method from view, kindly refer image shown below:

clip_image004[4]

Step4: Return Json result from action in special format from DBContext.

After an action called by view in jqGrid segment, it’s now action duty to return Json collection to caller to bind collection with jqGrid. Whenever action returns collection from as JsonResult it’s should be in a special format so that jqGrid could accept these values otherwise it will not load the values into grid. This is a code segment used at controller level as shown below:

  1: 1:  public JsonResult GetEmployee()
  2:   2:         {
  3:   3:             EmployeeEntities edb = new EmployeeEntities();
  4:   4:            // UsersContext u = new UsersContext();
  5:   5: 
  6:   6:             var jsonData = new
  7:   7:             {
  8:   8:                 total = 1,
  9:   9:                 page = 1,
 10:  10:                 records = edb.EmpRegistrations.ToList().Count,
 11:  11:                 rows = (
 12:  12:                   from emp in edb.EmpRegistrations.ToList()
 13:  13:                   select new
 14:  14:                   {
 15:  15:                       id = emp.Id,
 16:  16:                       cell = new string[] { 
 17:  17:                       emp.Address.ToString(), emp.City.ToString(), emp.Id.ToString(),emp.Name 
 18:  18:                       }
 19:  19:                   }).ToArray()
 20:  20:             };
 21:  21:             return Json(jsonData, JsonRequestBehavior.AllowGet);
 22:  22:         }
 23: 

 

Please have a look of image depicted below to understand the result set return by action at controller level.

clip_image006[4]

Here we are almost done, now run an application and Press F5 to see an output:

clip_image007[4]

I have developed this application in VS 2012 due to this, it’s tuff to upload here it doesn’t allow me upload more than 10 MB .Still I can share jqGrid reference files and controller.cs,view.cshtml and database .bak file(to create DBContext) as shown below.Kindly mail me.

clip_image008

Keep yourself ready for part2 to see more feature of jqGrid.

Thanks

Stay happy stay coding Smile

Tuesday, July 22, 2014

Coalesce function in sql server 2008

image

 

Coalesce(Add together different elements) used as a Case statement in SQl server.If the value in one of the columns is not available then use the value of the second column and if that is also not available, then use the third column. If none of the columns have the value, then null is returned for that value.

 

I’ve a table having structure as depicted below:

 

image

 

I will apply on Coalesce function on Category table to fetch information of three columns in a single column alias.it ignores null values of each columns.

I have created a query to retrieve desired information.kindly see an image depicted below:

image

 

if you notice in above shown image we have combined three columns(having null values also) together and get as single column Category.

 

Note: it doesn’t fit in that condition, if you have columns having values (other than Null) in a table and want to put into Coalesce function .

I’ve changed a structure little bit and added one more column Technology into Category table.Kindly see a Category table structure in an image shown below.

 

 

image

 

It returns value of first non-null column.I’ve changed a query as well and added “Technology” column Coalesce function.

Kindly refer image shown below.

 

image

 

Its very simple to learn and may be utilized in future.

Thanks

Sachin Kalia

Monday, July 21, 2014

Loop through Model items in ASP.NET MVC

Loop through Model items in ASP.NET MVC

 

MVC3

To loop through Model items in ASP.NET MVC view, use foreach loop in the Controller,which returns Collection of items

 

   1:  @model IEnumerable<BookStore.Models.Category>



Now write foreach loop
 

   1:  <body>
   2:      @if (Model != null)
   3:      {
   4:          foreach (var item in Model)
   5:          {
   6:          <ul id="menu">
   7:   
   8:              <li>
   9:                  @Html.DisplayFor(modelItem => item.BookName)
  10:              </li>
  11:              <li>
  12:                  @Html.DisplayFor(modelItem => item.Title)
  13:                  <br />
  14:              </li>
  15:              <li>
  16:                  @Html.DisplayFor(modelItem => item.BookId)
  17:              </li>
  18:          </ul>
  19:          }
  20:      }
  21:  </body>



 


ThanksSmile


To know more about MVC kindly go through with the links given below:

Wednesday, July 16, 2014

Points to remember: WCF Service

Points to remember: WCF Service

In this article I will explain some points about WCF service believe we should understand those points and their implementation also.

The main intent to write this article for those people who doesn’t understand the exact utilization of keywords and settings during WCF service creation and hosting

clip_image002

.

I have created a sample WCF service library and implement an interface having method Get info. Kindly refer an image depicted below for basic structure of web site:

clip_image004

If you notice an image shown above, I have also hosted this WCF service using console application.

Main intent to write this article starts from here.When I host this application and edit app.config file using ‘Edit WCF configuration”. Kindly see an image shown below:

clip_image005

This is a layout of app.config file as shown in image below.

clip_image007

Note:

Thus in order to generate proxies, you need metadata information. When you remove the serviceMetadata-line you say you are not providing Meta data in WSDL format.

But the line before, publishing your metadata in MEX, is still active, thus you can generate a proxy from those metadata. When you provide neither WSDL nor MEX formatted information, you cannot generate a proxy

Now let’s execute shown above steps more practically.

Point1:clip_image009

WCF service is up and running as shown in image below:

clip_image011

Initially service metadata is enabled as shown below:

clip_image012

I just paste a baseAddress url in browser, it provides us metadata in wsdl format as shown in image below:

clip_image014

But if I change it to “false” than it doesn’t provide you metadata in wsdl format. Kindly refer both images as shown below:

clip_image015

clip_image017

 

Point2:clip_image019

Now lets’ understand why mexHttpBinding is important from WCF perspective.

I’ve disabled “mexHttpBinding” code segment and host our service. It prompts us an error at time of adding Service reference to Client application.

clip_image021

‘IMetadataExchange’ contract is for enabling metadata for the service. This is required for adding service reference at WCF client side or it is a binding that returns metadata so you can build a proxy at the client side.

MEX endpoints are special endpoints that allow clients to receive the service’s metadata by using SOAP messages instead of http get requests. You can create MEX endpoint that can be accessed through http, https, tcp, and even named pipes.

Point 3:clip_image023

Third point is about to enable logging/tracing process in client application so that I could see what happen at time of calling an operation of WCF Service.

I’ve created a client application and added a reference of WCF Service, kindly see an image show below

clip_image025

To enable logging and tracing in client application edit app.config file. Kindly see below depicted image.

clip_image027

Go to Diagnostics and enables Log Auto Flush, MessageLogging and Tracing. Kindly see an image shown below:

clip_image029

Now go to Diagnostics-> Message Logging and set properties to true as shown in image below to log the exact information.

clip_image031

After setting properties to true it asks you to update your app.config file, press yes to all. And go through once with updated config file. Now we are done with all requirements and ready to consume our service via client. Press F5.

It will be first appearance of you client application as shown below in image:

clip_image033

I put some value in text box and press on GetInfo button, See the result below.

clip_image035

Now look at the .svclog files exist in root folder of client application as shown in image below:

clip_image037

Note: Don’t forget to refresh this folder once.

Double click on the app_messages file and see the result.

clip_image039

Response:

clip_image041

GreatJ .

I belief we learnt remarkable points about wcf service, which we may face in daily routine work.

You can also have a look at MVC-related articles here:

clip_image043

Keep coding and Smile Smile

Tuesday, July 15, 2014

Dictionary requires a model item of type System.Collections.Generic.IEnumerable in MVC 3

MVC

I encountered an error while implementation of return multiple models to single view.

Kindly visit an article for reference.

Return Multiple Models in single View in MVC3

An error was occurring on routine basis.Initially I found challenge to find the root cause of this.

Later I understood an error and change my approach to overcome on this.

In this blog I am sharing the way to resolve this error.

Whenever I run my application and paste the following URL in browser http://localhost:60346/Home/rsvpform , it prompts me an error:

The model item passed into the dictionary is of type 'MVCSample.Models.ParentModel', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1[MVCSample.Models.ParentModel]'.

The reason behind the View “(.cshtml) expects the IEnumerable model type. “as I’ve set below for sample app.

clip_image001

Now figure out the reason for occurrence of an error, it generates an error when we are returning only of base type model class object as an example below:

clip_image002

So point of interest is whenever you return a model type object it must be sync with view model type.

If I uncomment the above three lines as depict also in below image it will run as expected, because of this is we are returing viewModelList object as Enumerable type .

clip_image003

More Summarized words are, Model declaration in View and the model being return from Controller class must be sync with each other.

clip_image005

 

To know more about MVC kindly go through with the links given below:

· Smart Working With Custom Value Providers in ASP.Net MVC

· Invoke Action With Model Binders in MVC

· Extension Helpers Method in MVC

· Custom Button With TagBuilder Using MVC Razor Engine

· Precompiled Razor View Using RazorGenerator MVC and PreCompiledViewEngine in MVC 4

· RETURN MULTIPLE MODELS IN SINGLE VIEW IN MVC3

· CALL CONTROLLER ACTION METHOD FROM JQUERY USING AJAX

· EXECUTION ORDER OF FILTERS IN MVC 4 WITH PRACTICES: IMPORTANT FAQ

· MEANING OF SCAFFOLDING IN MVC

· REMOVE AMBIGUTY OF CONTROLLER NAMES IN MVC APPLICATION

· CUSTOM BUTTON WITH TAGBUILDER TECHNIQUE USING MVC RAZOR ENGINE

· CONVERSION HELPERS IN MVC RAZOR: VALIDATING POSTED DATA

Thanks

Enjoy Coding and Stay Happy Smile