Showing posts with label MVC. Show all posts
Showing posts with label MVC. Show all posts

Wednesday, August 21, 2019

MVC Ajax WebGrid with Sorting and Paging

In this Step by step MVC Ajax WebGrid with Sorting and Paging in 10 Minutes 
   we see how to build an Ajax enabled WebGrid using an jQueryUI Theme  in 10 minutes, following this simple steps :

1) Use MVC scaffolding and build your Model and Views
2) Select a jQueryUI Theme & download it
3) In the "Index" View, replace the Table with a WebGrid and enable Ajax


All the code in this tutorial , can be downloaded from the following GitHub repository:
https://github.com/CarmelSoftware/MVC_WebGrid

This is how this sortable paged Ajax WebGrid is shown in the Ripple Mobile Emulator , Nexus Galaxy settings:


MVC Ajax WebGrid with Sorting and Paging


MVC Ajax WebGrid with Sorting and Paging in 10 Minutes


The whole process of creating an Ajax WebGrid with a jQueryUI Theme , is as following:

1) Use MVC scaffolding and build your Model and Views:

First build your MVC project using EDM & Controller scaffolding.


2) Select a jQueryUI Theme & download it

Browse to http://jqueryui.com/themeroller/  , select your Theme, and download it.
After you unzip the folder, you'll see several files in it.
You do not need all of them. Just copy the following 2 files and folder to your MVC project:
MVC Ajax WebGrid with Sorting and Paging1



Paste the files inside your MVC project as follows:

MVC Ajax WebGrid with Sorting and Paging2


As you can see, the ONLY files that we'll use from the jQueryUI theme are the following:

1) JS folder :
     "jquery-X.X.X.min.js" (here get the latest version of jQuery)
     "jquery-ui.min.js"

2) CSS folder :
     "jquery-ui.css"


Add the following references to the _Layout file:

MVC Ajax WebGrid with Sorting and Paging3

There is no need of referencing the "images" folder.
Also, you get the latest version of jQuery framework : at this moment, that version is 2.1.4


3) In the "Index" View, replace the Table with a WebGrid and enable Ajax

Then go to the "Index" view, and comment the Table that was scaffolded there.
Add the following markup to replace it:

<link href="~/Content/index.css" rel="stylesheet" />

@{ var grid = new WebGrid(Model, new[] { "Title", "DatePosted", "MainPicture" }, rowsPerPage: 3, ajaxUpdateContainerId: "gridDIV"); }


<div id="gridDIV">
@grid.GetHtml(tableStyle:"webgrid-table",headerStyle:"webgrid-header",

    columns: new[] {

        grid.Column("ID",format:(item) =>  item.GetSelectLink(item.BlogID.ToString()) ) ,
        grid.Column("Title",format:@<a href='/Blog/Comments/@item.BlogID'><b>@item.Title</b></a>),
        grid.Column("DatePosted","DatePosted", (item) => String.Format("{0:dd/MM/yyyy}", item.DatePosted != null ? item.DatePosted : DateTime.Now )),
        grid.Column("Picture",format:(item) =>
        { return new MvcHtmlString("<a href='/Blog/Comments/" + item.BlogID +
            "'><img src='/Images/"+item.MainPicture+"' style='width:100px;height:100px;'></img></a>");
        }),
  
        grid.Column(
            format:@<div class="ActionsTH">
            @Html.ActionLink("Edit", "Edit", new { id=item.BlogID })
            @Html.ActionLink("Details", "Details", new { id=item.BlogID })
            @Html.ActionLink("Delete", "Delete", new { id=item.BlogID })
        </div>)
    })
</div>

This code enable Ajax on the Grid, which comes already with Sorting and Paging functionality.
Of course, customize this code with your Model's properties.

As you can see, we also reference a "~/Content/index.css" file:
Inside this file, i added background style found in the "images" folder, such as "images/ui-bg_fine-grain" corresponding to the Theme "Pepper-Grinder" .
If you select another Theme, replace the backgrounds accordingly.
Create this CSS file in the Content folder , and paste this style in it:


body {
    background: #f7f3de url("images/ui-bg_fine-grain_15_f7f3de_60x60.png") 50% 50% repeat;
}

.webgrid-table {
    font: italic 11px Verdana;
    width: 100%;
    display: grid;
    border-collapse: separate;
    border: solid 1px #98BF21;
    background: #f8f7f6 url("images/ui-bg_fine-grain_10_f8f7f6_60x60.png") 50% 50% repeat;
    padding: 5px 5px 5px 5px;
    text-align: center;
}

.webgrid-header th {
    width: 150px;    
    background: #eceadf url("images/ui-bg_fine-grain_10_eceadf_60x60.png") 50% 50% repeat;
    color: #FFFFFF !important;
    font: 900 14px Verdana !important;
    padding: 5px 5px 5px 5px;
    text-align: center;
}

.ActionsTH {
    width: 50px;
    background: #eceadf url("images/ui-bg_fine-grain_10_eceadf_60x60.png") 50% 50% repeat;
    color: #FFFFFF !important;
    font: 900 14px Verdana !important;
    padding: 5px 5px 5px 5px;
    text-align: center;
    width: 180px;
}

.webgrid-footer, .webgrid-footer a {
    background-color: #c67f1c;
    color: #FFF;
    font: 900 14px Verdana;
    padding: 3px 3px 3px 3px;
}

.webgrid-alternating-row {
    background-color: #e5d773;
    padding: 5px 5px 5px 5px;
}

.title-column {
    font: 900 13px Verdana;
    text-align: center;
}

.webgrid-img {
    width: 150px;
    height: 150px;
}

.webgrid-table a {
    text-decoration: none;
    color: #808080;
}


Important:
If you do not see the Ajax working (), it is because the jQuery scripts are lacking.
Just cut the jQuery.js file from the _Layout file to the <head> tag :
    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/jqueryui")
</head>


THE END

To use a Mobile devices Emulator, take a look at this short tutorial on installing the FREE Ripple Emulator.


That's all. Our WebGrid will be displayed this way:
MVC Ajax WebGrid with Sorting and Paging4

MVC Ajax WebGrid with Sorting and Paging5

MVC Ajax WebGrid with Sorting and Paging6





      by Carmel Schvartzman


כתב: כרמל שוורצמן



Thursday, March 31, 2016

Install jQueryUI Themes in your MVC App in 5 Minutes

In this Step by step Install jQueryUI Themes in your MVC App in 5 Minutes 
   we see how to get your chosen jQueryUI Theme and use it inside your MVC application in 5 minutes, following this simple steps :

1) Select a Theme & download it
2) Select ONLY the script and style files you need
3) Reference them from your HTML5 file


This is how this jQueryUI Application is shown in the Ripple Mobile Emulator , for Nexus Galaxy:

Install jQueryUI Themes in your MVC App in 5 Minutes

Install jQueryUI Themes in your MVC App in 5 Minutes 1



Install jQueryUI Themes in your MVC App in 5 Minutes


The whole process of downloading a jQueryUI Theme , selecting the files you need , and using the Theme in your MVC app, are as following:

1) Select a Theme & download it:

Browse to jQueryUI.com , and open the "Themes" page:

Install jQueryUI Themes in your MVC App in 5 Minutes

Select from the ThemeRoller the Theme you want to apply to your web site , clicking the "Download" button :

Install jQueryUI Themes in your MVC App in 5 Minutes

We use the former version because it is more stable .
Check all checkboxes if they are not :


Install jQueryUI Themes in your MVC App in 5 Minutes 2

Download the theme to your machine.


2)  Select ONLY the script and style files you need:

Unzip and open the downloaded theme, as you can see here:

Install jQueryUI Themes in your MVC App in 5 Minutes 3

Copy- paste the CSS and JS folders to your MVC project.
The ONLY files that the theme will need are the following:

1) JS folder :
     "jquery-X.X.X.min.js"
     "jquery-ui-1.9.2.custom.min.js"

2) CSS folder :
     "jquery-ui-1.9.2.custom.css"



Inside the JS folder, replace the jQuery framework script file that comes with the jQueryUI theme, with the latest version:


Install jQueryUI Themes in your MVC App in 5 Minutes

And replace the corresponding reference in the HTML5 file :


Install jQueryUI Themes in your MVC App in 5 Minutes 4



To take advantage of a Mobile Emulator, take a look at this short tutorial on installing the FREE Ripple Emulator.


That's all. Our jQueryUI theme will be displayed this way:

Install jQueryUI Themes in your MVC App in 5 Minutes 5

Install jQueryUI Themes in your MVC App in 5 Minutes 6

Install jQueryUI Themes in your MVC App in 5 Minutes 7






      by Carmel Schvartzman


כתב: כרמל שוורצמן




Thursday, August 6, 2015

jQuery Plugin to serialize an HTML5 Form into a JSON object


jQuery Plugin to serialize an HTML5 Form into JSON

by Carmel Schvartzman - The MVC Club


A custom jQuery Plugin for serializing a Form into a JSON object to send in an HTTP request to the server.
This elegant Plugin is a high performance code to transform the data inside an HTML5 Form , into a JSON object serialized to a string. This string can then be sent inside the body of an HTTP POST, HTTP PUT or HTTP PATCH request, in order to be preserved in some database at server side.
This jQuery plugin can be referenced by an MVC View, and of course can be used by any HTML5 web page.
Requisites:
1) your HTML5 web page has to reference the jQuery framework
2) only the fields that have a "name" attribute will be serialized in a JSON object. All other fields that you don't want to serialize, such as hidden identity fields and anything like that, will be ignored.
The requisites for the Form input fields serialization are according to the www.w3.org Recommendation on web Forms .
This plugin uses jQuery utilities such as the serializeArray method .
This Plugin can be downloaded from the following GitHub repository:
https://github.com/CarmelSoftware/jQueryPlugin_FormSerializer

Snapshots:






The Form is serialized into the JSON object as follows:






Usage:

This utility jQuery Plugin is used as follows:






The Plugin's code :


All the Form's fields have to have a "name"  :


The Plugin usage is explained in the following Tutorial:
By Carmel Schvartzman

Enjoy MVC !!!


פיתוח: כרמל שוורצמן

Tuesday, May 27, 2014

Step By Step How to create a Nested WebGrid in MVC 4 in 10 minutes

In this tutorial we'll learn how to create a WebGrid nested inside another Webgrid with paging capabilities in MVC 4 in 10 minutes. The parent WebGrid will expose data dynamically loaded from database and will contain another WebGrid exposing another list of data represented by a one to many relationship.
The parent grid will display a list of Blog posts, while the nested webgrid will display the comments attached to each post.

We'll want to create a parent-child relationship between two webgrids , showing as follows:



This tutorial will use data fetched from the Entity Framework, exposing the following classes related by a one-to-many relationship:





To create the WebGrids we must create our own View, and it will not be difficult if we take advantage of the Scaffolding capacities of the MVC environment. So first let's create a new Controller called "BlogController", automatically scaffolding the necessary Views to cope with the CRUD functionality requirements. So right click over the Controllers folder, and add a new Controller:



Name it "BlogController", and select the template "MVC Controller with read/write actions and views, using Entity Framework":



The Context to use will be of course the one you named while creating your Entity Framework Data Model, and the Model will be the Blog class, because we'll be creating, updating and deleting Blog objects.
After you create the Controller, open it and take a look at the Action Methods created for you: there are action methods for displaying the list of Blog posts (Index method), to create new ones , to update them, and to delete:




Open the Views folder and see the Views that were created for you:



First of all, let's add a link to the _Layout .cshtml file Menu, in order to browse to the Blog web page from the Home page:




As you see, we got all CRUD functionality. But now we want a WebGrid with paging-sorting capabilities,  instead of a table. So we'll replace the <TABLE> with an WebGrid Html Helper: open the Index View:





And comment the whole  <table> tag:



Next, we'll instantiate a WebGrid, using an overload of the constructor method, and we'll set as its arguments the data included in the Model (an IEnumerable<Blog>), and the <div> tag to be updated when ajax calls in case you need to include links or buttons in your webgrids:




Now we display the markup of the WebGrid using the GetHtml() WebGrid method:




Notice we formatted all the fields we need, in order to properly display the dates and pictures. We also add the style to the grid (the CSS stylesheet will be added afterwards).
Now is time to add the nested gridview, in an appended column which we call "Comments":





In this details child gridview, we displayed the comments for each post, and also we formatted it with some CSS style.
The two grids, parent and child, are inside a <div> tag for ajax purposes, and will finally look as follows:




Add a new .css stylesheet file to the "Contents" folder:



Name the .css as GridStyle:




In the stylesheet we include all the style for the WebGrid, footer, header, hyperlinks, even the style for displaying adecuately the pictures:



The code (to copy-paste) is the following:
        .webgrid-table
        {
            font:italic 11px Verdana;
            width: 100%;
            display:grid;
            border-collapse: separate;
            border: solid 1px #98BF21;
            background-color: #f0c9a0;
            padding: 5px 5px 5px 5px;
        } 
        .webgrid-header
        {
            background-color: #c67f1c !important;
            color: #FFFFFF !important;
            font: 900 14px Verdana !important;
            padding:5px 5px 5px 5px;            
            text-align: center;
            
        }
        .details-div
        {
            background-color: #c67f1c !important;
            color: #FFFFFF !important;
            font: 900 14px Verdana !important;
            padding:5px 5px 5px 5px;
            text-align: center;
            
        }
        .SecondaryGrid
        {
            background-color: #c67f1c !important;
            color: #000 !important;
            font: 600 11px Verdana !important;
            padding:5px 5px 5px 5px;
            text-align: center;
            width:180px;
        }
        .webgrid-footer, .webgrid-footer a
        {
            background-color: #c67f1c;
            color: #FFF;
            font: 900 14px Verdana;
            padding:3px 3px 3px 3px;
        }
        .webgrid-alternating-row
        {
            background-color: #e5d773;
            padding:5px 5px 5px 5px;
        }
        .title-column
        {
            font:900 13px Verdana;
            text-align:center;
        }
        .webgrid-img
        {
            width: 150px;
            height: 150px;
        }


Finally we add a <link> tag in the _Layout file, to include the .css in the Index View:


Buid (F6) and run your app (CTL-F5) , to get this presentation UI:



Notice that you can do paging:




In this tutorial we've learned how to create a WebGrid nested inside another Webgrid with paging capabilities in MVC 4 in 10 minutes, exposing data dynamically loaded from database and sent by the Action method from the web server.  
That's all!! 
Happy programming.....
        By Carmel Schvartzman
כתב: כרמל שוורצמן







Monday, May 26, 2014

Step By Step How to create partial views with Child Action Methods

        By Carmel Schvartzman

In this tutorial we'll learn how to create a partial view using Child Action Methods in MVC 4. Child Methods allow us to reuse code and markup, fully applying the DRY Software Paradigm ("Don't Repeat Yourself") , and avoiding the WET ("Write Everything Twice") approaches. The Child Actions cannot be invoked via regular user requests, instead they are invoked directly from the View. A Child Action method is to an Action method as a Partial View is to a View. 

In MVC there are 4 similar methods to render a Partial View, and it's important that we decide which one to use according to their properties:
1) The most widely used method is RenderPartial(), which is fast because it writes directly to the HTTP response stream, and is easy to use as it doesn't require to code a Child Action. But the data for the partial view must already be loaded in the view Model. The problem with this approach is, we can be tempted to manipulate the data INSIDE the PRESENTATION LAYER, to send it to the partial view. When we pass data from a view to another view we are specifying how to instantiate entity objects, and that shoud be a Bussiness Layer task.

2) Partial() is essentially the same thing but, instead RenderPartial(), it returns a string with HTML encoding, and you can use it to instantiate a variable if you like.
3) RenderAction() requires 
from the developer to code a Child Action, and therefore you could separate presentation layer from the Repository or Bussiness Layer. Is fast because it writes directly to the HTTP response stream.

4) Action() method is the same but it returns a string with HTML encoding. Using Action() you leave to the Controller (Child Action) the task of deciding which partial view to render. That way we leave to the Controller the responsability to make traffic decisions and to invoke Bussiness Logic. Also, this way we can make refactoring more neatly.
Child Actions are useful in building widgets and embedding them in the View. 

In this tutorial we'll create a Partial View and render it using an Action() call, being the presentation layer as this:



We'll display all Posts in a <TABLE> saved in a Partial View, and all Bloggers in another table from another Partial View. Each Partial View will be populated by a different Controller's Child Action.

First of all, let's create a new View inside the Shared folder at Views. This will be the "PostsList" Partial View:


 Now   for the "PostsList" Partial View, select "Blog" class for the scaffolding Model, and "List" for the template:



Open the _PostsList Partial View and take a look at the markup. It will be something like this (depending on your Entity Model):

Add the classes style definitions, CSS style that we'll add in a little bit, and look at the loop built by the template:

Notice we added the style classes to the <table> tag. Also, we've applied some formatting to properly display dates and pictures.

Now in order to display some style , add a new .css stylesheet file to the "Contents" folder:



Name the .css as GridStyle:




In the stylesheet we include all the style for the WebGrid, footer, header, hyperlinks, even the style for displaying adecuately the pictures:



The code (to copy-paste) is the following:
        .webgrid-table
        {
            font:italic 11px Verdana;
            width: 100%;
            display:grid;
            border-collapse: separate;
            border: solid 1px #98BF21;
            background-color: #f0c9a0;
            padding: 5px 5px 5px 5px;
        } 
        .webgrid-header
        {
            background-color: #c67f1c !important;
            color: #FFFFFF !important;
            font: 900 14px Verdana !important;
            padding:5px 5px 5px 5px;            
            text-align: center;
            
        }
        .details-div
        {
            background-color: #c67f1c !important;
            color: #FFFFFF !important;
            font: 900 14px Verdana !important;
            padding:5px 5px 5px 5px;
            text-align: center;
            
        }
        .ActionsTH
        {
            background-color: #c67f1c !important;
            color: #FFFFFF !important;
            font: 900 14px Verdana !important;
            padding:5px 5px 5px 5px;
            text-align: center;
            width:180px;
        }
        .webgrid-footer, .webgrid-footer a
        {
            background-color: #c67f1c;
            color: #FFF;
            font: 900 14px Verdana;
            padding:3px 3px 3px 3px;
        }
        .webgrid-alternating-row
        {
            background-color: #e5d773;
            padding:5px 5px 5px 5px;
        }
        .title-column
        {
            font:900 13px Verdana;
            text-align:center;
        }
        .webgrid-img
        {
            width: 150px;
            height: 150px;
        }




Now open the "Index" View and invoke the Child Action using the Action() method:



Notice that we added a <link> tag , to include the .css in the Index View:



Finally, let's code the Child Method, creating first the Context in the Controller:



Now append the Child Action:
Notice that this Child Action deals directly with the data from a Repository, and also can decide whether to render some specific Partial View or another one.


Save and run the application:



That's all!! 
In this tutorial we've learn how to create a partial view using Child Action Methods in MVC 4, thus allowing us to reuse code and markup in future refactoring.  

Happy programming.....


כתב: כרמל שוורצמן