Friday, January 11, 2019

Partial Page in ASP.NET MVC

How to use the partial pages in ASP.NET MVC
I was working on a ASP.NET MVC project where requirement was to create dashboard for the user and display the request based on their status in different tables. Initially, I thought to create tables using JavaScript frameworks. But there was another side of story, requirement was to add the CRUD operations on each record. I am not saying that this is not achievable in JavaScript but I was looking for the simple solution.
I explore multiple options and found that partial page implementation is the right solution of my problem. I followed below steps to implement the partial page functionality for my requirement. If you think you have a different/simple approach feel free to leave your suggestion in the comment section down below.
Step 1. Form Layout
<div class="form-horizontal">
    <div class="col-md-6">
        <h4>My Draft SOW</h4>
        <div id="draftSow"></div>
    </div>
    <div class="col-md-6">
        <h4>Pending SOW</h4>
        <div id="pendingSow"></div>
    </div>
    <div class="col-md-12">
        <h4>Approved SOW</h4>
        <div id="approvedSow"></div>
    </div>
</div>
Step 2. JavaScript code to render the partial page
$(document).ready(function () {
       //Draft
       //debugger;
       $.ajax({
           type: "GET",
           url: "@Url.Action("DisplaySow", "Home")",
           data:{"typeOfSOW":"Draft"},
           datatype: "json",
           contentType: "application/json; charset=utf-8",
           success: function (result) {
               $('#draftSow').html(result);
           },
           error: function (data) { }
       });

       //Pending
       $.ajax({
           type: "GET",
           url: "@Url.Action("DisplaySow", "Home")",
           data: { "typeOfSOW": "Pending" },
           datatype: "json",
           contentType: "application/json; charset=utf-8",
           success: function (result) {
               $('#pendingSow').html(result);
           },
           error: function (data) { }
       });

       //Approved
       $.ajax({
           type: "GET",
           url: "@Url.Action("DisplaySow", "Home")",
           data: { "typeOfSOW": "Approved" },
           datatype: "json",
           contentType: "application/json; charset=utf-8",
           success: function (result) {
               $('#approvedSow').html(result);
           },
           error: function (data) { }
       });
   });
Step 3. Action method in controller
[HttpGet]
       public ActionResult DisplaySow(string typeOfSOW)
       {
           //Set Status as Pending Approval
           //Models.SOW uObject = JsonConvert.DeserializeObject(objSOW.ToString());
           ListSOWDisplay> lstSowDisplay = new List<SOWDisplay>();
           Models.SOWDisplay objsow;
           if (typeOfSOW == "Draft")
           {
               objsow = new SOWDisplay() { SOWId = "1", ProjectName = "Test1", CurrencyName = "USD", Location = "Onsite", SOWStartDate = "01/01/2018", SOWEndDate = "12/31/2018" };
               lstSowDisplay.Add(objsow);
               objsow = new SOWDisplay() { SOWId = "2", ProjectName = "Test2", CurrencyName = "CAD", Location = "Offshore", SOWStartDate = "01/01/2018", SOWEndDate = "12/31/2018" };
               lstSowDisplay.Add(objsow);
               return PartialView("_Draft", lstSowDisplay);
           }
           else if (typeOfSOW == "Pending")
           {
               objsow = new SOWDisplay() { SOWId = "3", ProjectName = "Prj1", CurrencyName = "GBP", Location = "Onsite", SOWStartDate = "01/01/2018", SOWEndDate = "12/31/2018" };
               lstSowDisplay.Add(objsow);
               objsow = new SOWDisplay() { SOWId = "4", ProjectName = "Prj2", CurrencyName = "USD", Location = "Onsite", SOWStartDate = "01/01/2018", SOWEndDate = "12/31/2018" };
               lstSowDisplay.Add(objsow);
               return PartialView("_Draft", lstSowDisplay);
           }
           else
           {
               objsow = new SOWDisplay() { SOWId = "0", ProjectName = "Prj0", CurrencyName = "USD", Location = "Onsite", SOWStartDate = "01/01/2018", SOWEndDate = "12/31/2018" };
               lstSowDisplay.Add(objsow);
               objsow = new SOWDisplay() { SOWId = "-1", ProjectName = "Prj", CurrencyName = "USD", Location = "Onsite", SOWStartDate = "01/01/2018", SOWEndDate = "12/31/2018" };
               lstSowDisplay.Add(objsow);
               return PartialView("_Draft", lstSowDisplay);
           }
           
       }
Step 4. Partial Page
@model IEnumerableSOWDisplay>
@{
   var draftGrid = new WebGrid(Model, canPage: true, rowsPerPage: 10, canSort: true, ajaxUpdateContainerId: "draftList");
}
@draftGrid.GetHtml(tableStyle: "table",
   headerStyle: "header",
   alternatingRowStyle: "alt",
   selectedRowStyle: "select",
   columns: draftGrid.Columns(draftGrid.Column("ProjectName", "Project Name"),
draftGrid.Column("CurrencyName", "Currency Name"),
draftGrid.Column("Location", "Location"),
draftGrid.Column("SOWStartDate", "Start Date"),
draftGrid.Column("SOWEndDate", "End Date"),
draftGrid.Column(columnName: "Action", format: (item) => Html.ActionLink("Edit", "Create", new { sowId = item.SOWId }))
))
Step 5. Model
public class SOWDisplay
   {
       public string SOWId { get; set; }
       public string ProjectName { get; set; }

       public string CurrencyName { get; set; }

       public string Location { get; set; }

       public string SOWStartDate { get; set; }

       public string SOWEndDate { get; set; }



   }

jsGrid in Asp.Net MVC Application

I was working one a Asp.Net MVC application where I was using the Web Grid to display the data based on the selected search criteria. It was working great but client asked me to use the jsGrid instead of Web Grid as it has many ready to use features like (Edit, Delete, Search, etc..). 

Initially, jsGrid gave me very hard time to display the data in it but after few hit and trial I manage to display the data. After spending couple of hours on jsGrid, I started liking it.

In this article, I am going to explain how to use the jsGrid to display the data and some other tactics in very easy steps. I am building the application in ASP.NET MVC.

Step 1. Content delivery network (CDN) of jsGrid and jQuery libraries are as below
https://cdnjs.cloudflare.com/ajax/libs/jsgrid/1.5.3/jsgrid.min.css
https://cdnjs.cloudflare.com/ajax/libs/jsgrid/1.5.3/jsgrid.css
https://cdnjs.cloudflare.com/ajax/libs/jsgrid/1.5.3/jsgrid-theme.min.css

https://code.jquery.com/jquery.min.js

Step 2. jsGrid – HTML code – We need to add a division (DIV)

<div id="searchResult" style="width:auto" />

Step 3. Javascript code to set the properties of jsGrid. In this example I am making a POST request to get the data based on the supplied parameter. Also, I am not using the CRUD operation on the data that’s why I am hiding the delete and edit feature of jsGrid.

$('#searchResult').jsGrid({
            height: "auto",
            width: "100%",
            filtering: false,
            sorting: true,
            paging: true,
            autoload: true,
            controller: {
                loadData: function (filter) {
                    //Send the post request
                    var searchCriteria = {
                        "ReceiverName": $('#txt_RecName').val(),
                        "ClientName": $('#txt_ClientName').val(),
                        "RefDesc": $('#txtRefDesc').val(),
                        "SenderName": $('#txt_SenderName').val()
                    };
                    return $.ajax({
                        url: "GetResultData",
                        type: "POST",
                        contentType: "application/json; charset=utf-8",
                        datatype: "json",
                        data: JSON.stringify(searchCriteria)
                    });
                }
            },
            pageSize: 2,
            pageButtonCount: 5,
            pageIndex: 1,

            noDataContent: "No Record Found",
            loadIndication: true,
            loadIndicationDelay: 500,
            loadMessage: "Please, wait...",
            loadShading: true,
            fields: [
                {
                    name: "Eligible for R&R",title: "Eligible for R&R", type: "text", width: 50,
                    itemTemplate: function (value, item) {
                        return '
)>Edit
';
                    }
                },
                { name: "CollaborationID", title: "Collaboration ID", type: "text", width: 100 },
                { name: "SendingOpco", title: "Sending Opco", type: "text", width: 100 },
                { type: "control",deleteButton:false,editButton:false }
            ]
        });

Step 4 Data Contract
namespace Models
{
    public class AnnualReview
    {
        public string CollaborationID { getset; }
        public string SendingOpco{ getset; }
        public string Sender { getset; }
    }
}
Step 5. Controller code, You need to create AnnualReview data contract and add two properties (CollaborationID and SendingOpco) to it

[HttpPost]
        public JsonResult GetResultData(SearchCriteria obj_Search)
        {
            List<AnnualReview> lstResult = new ListAnnualReview>() {
                new Models.AnnualReview() {CollaborationID="CSID0001",SendingOpco="Marsh"},
                new Models.AnnualReview() {CollaborationID="CSID0002",SendingOpco="Mercer"},
                new Models.AnnualReview() {CollaborationID="CSID0003",SendingOpco="Mercer"}
            };
            return Json(lstResult.ToArray(), JsonRequestBehavior.AllowGet);
        }


Step 6. If code compile and executed without any issue you will see the data into the jsGrid.


Checkbox list in ASP.Net MVC



Recently, I got an assignment when I need to show the items in checkbox list format. It was very easy in ASP.NET web form because it has CheckBoxList control but it was bit challenging for me to show the items in checkbox list in ASP.NET MVC as there are basic controls available.

In this post I am going to explain you how to build the CheckBoxList control in ASP.NET MVC using the basic control and Razor engine following the steps listed below. Let’s get started

Step 1. First thing first, View Code

@model SOW.Models.DropdownValues
    <table>
        <tr>
            <td class="td_12per">Select Country:</td>
            <td class="td_12per">
                <div class="divCheckbox" id="divSelCountry">
                    @foreach (var item in Model.SendingCountryList)
                    {
                        <div class="checkbox" style="border:1px solid graymargin-top:-1px;margin-bottom:0px;width:100%;padding-left:2px">
                            <label>
                                <input type="checkbox"
                                       name="SelectedItems"
                                       value="@item.Value" id="SCL_@item.Value" /> @item.Text
                                </label>
                            </div>
                    }
                </div>
            </td>
</tr>
</table>

Step 2. Model
public class DropdownValues
    {
        public DropdownValues()
        {
            CountryList = new List<SelectListItem>();
        }
        public IList<SelectListItem> SendingCountryList { getset; }
    }

Step 3. Controller – Create a controller name CheckboxListController
public class CheckboxListController : Controller
    {
        // GET: AnnualReview
        public ActionResult CheckboxList()
        {
DropdownValues dv = new DropdownValues();
            //Sending Country List
            dv.CountryList.Add(new SelectListItem { Text = "Select All", Value = "SelectAll" });
            dv. CountryList.Add(new SelectListItem { Text = "Australia Australia Australia Australia", Value = "Australia" });
            dv. CountryList.Add(new SelectListItem { Text = "Austria", Value = "Austria" });
return View("ViewName", dv);

        }
}

Step 4. Final Output