European ASP.NET MVC Hosting

BLOG about Latest ASP.NET MVC Hosting and Its Technology - Dedicated to European Windows Hosting Customer

ASP.NET MVC 6 Hosting - HostForLIFE :: Creating ASP.NET MVC APP With WCF Service

clock October 18, 2022 09:37 by author Peter

Use the following to create an ASP.NET MVC APP with a WCF Service using an ADO.NET Entity Data Model:
SQL Server DB -> WCF Service (ORM) -> MVC Application -> User (Browser).

This small app works in a 4-tier architecture as in the following:
    User Tier
    MVC app Tier
    WCF Service Tier
    SQL Server Tier

Project 1: WCF Project
Step 1
Go to VS 2012 and select "File" -> "New Website" then select "WCF Service" then provide the name “WcfMvc”.

Click "OK".

Step 2
Go to the Solution Explorer then go to "WcfMvc application" then right-click on it then seelct "Add" -> "Add new item" -> "Add ADO .Net Entity data model". Then click the "Add" button then place the file in the App_code Folder.

Step 3
Then the Entity Data Model Wizard will be shown. Select "Generate data from database" then click the "Next" button .

Step 4
Choose your data connection. I’m selecting My “ran” database of SqlServer 2012.
Activate the radio button “Yes include the sensitive data in the connection string”.
Save the connection string in the config file by enabling the check box “Save entity connection setting in web.config as:“ then click the "Next" button.

Or

go to the new connection and create your connection then provide the server name then provide the authentication type then select either Windows Authentication or SQL Authentication then provide the database name then click the "Ok" button. A new connection will then be generated.

Activate the Radio Button “Yes include the sensitive data in the connection string”.

Save the connection string in the config file by enabling the check box “save entity connection setting in web.config as: “ then click the "Next" button.

Step 5
Choose which database object you want in your model.

I’m selecting the “Customer” table. The table definition is as follows:
Create table customer
Custno int constraint pk primary key,
custname varchar(30) not null,
custcity varchar(30),
custbalance money);


You can use the above table or create your own table and use it

Then provide a Model Namespace of your choice.. I’m using “ranjeet” Namespace.

Click the "Finish" button.

Please ensure that in the Solution Explorer under the App_code folder the Model.edmx file has been created.

Your entity data model is ready for use.


Step 6
Go to Solution Explorer then expand the App_code Folder then go to the Iservice.cs file.

Step 7
Delete the Getdata() and GetDataUsingDataContract() methods.

Then

I’m writing one method GetCustomer() as follows.

Step 8
Then go to the Sevice.cs file and implement the method declared in the IService.cs interface.

In the Service.cs file right-click the Iservice Interface then select "Implement Interface" -> "Implement Interface".

Delete the already present method in the Service.cs the file.

And write the following code in the “public List<customer> GetCustomer()” method.

“ranEntities1” is a class name given when the connection is created.

Step 9
Open the Service.svc file and now run the project.
A new window will open; copy the URL present in that window and paste it into any text file. This URL will be used in the next project.

Project 2: MVC Application 4
Step 1

Ensure that the WCF project is open then start another instance of VS 2012. Then go to "File" -> "New" -> "Project..." then create an ASP.NET MVC 4 Web Application. Name it “MvcWcfApplication” then click "ok" Button. Then select the Project Template “Internet Application” then click the "Ok" button.

Step 2
Create a Proxy using “Add Service Reference” by right-clicking on MvcWcfApplication in the Solution Explorer.

(Note: Proxy is a class that converts a local request into a remote request.)

A new window will open. Paste the URL that you copied from the WcfMvc project into the Address TextBox then click "Go".

In other words, a proxy class is created successfully..

(Caution: if it has been created and in the project you can’t use the ServiceReference1 namespace Pl then don’t worry; it is a VS 2012 Automation Error. To solve it go to the Solution Explorer then select ServiceReference1 then right-click on it then select "Configure Service Reference". A new window will open then in it uncheck the “Reuse types in referenced assemblies” checkbox..)

A serviceReference1 will added into your project.

Step 3
Now add a new Controller then in Solution Explorer seelct "Controller" then right-click on it then select "Add Controller" (Ctrl+m, Ctrl+c).

Name it DbController. Click the "Add" button.


Step 4
Add the following code in the DbController.cs file.

Please build the project.

Step 5
Now right-click inside the Index() Method then select "Add View" (Ctrl+m, Ctrl+v) then click on “Create a Strongly Typed View” checkbox then select the Model Class we created, in other words “customer (MvcWcfApplication.ServiceReference1)” then select "Scaffold template List"then click the "Add" button.


Step 6
Run the application.
In the browser type: http://localhost:<Port>/Db

And see the results. All the data in the customer table is shown below the using WCF Service.

If you like this then please comment below.



ASP.NET MVC Hosting - HostForLIFEASP.NET :: Generating An Excel File Through A List Of Objects In ASP.NET MVC

clock October 10, 2022 09:21 by author Peter

Today I will show you how to generate an excel file from a list of objects in C#. To do this, several plugins allow you to do this work in a global way. In this work, I will try to create a very simple and generic method to generate an excel file from a list of objects whatever their nature.


Step 1
Create a new ASP.NET MVC project.

Give a name to this project. for example "ExcelGeneratingApp".

Choose the MVC type.

Step 2

Create a class "ExcelLib.cs" in the models folder of the application.

Step 3

Add "ClosedXML" library from Nuget Package Manager.

Add class named "Employee.cs" for example.
using System.ComponentModel;
namespace ExcelGeneratingApp.Models
{
public class Employee
{
[DisplayName("Identity number")]
public int ID { get; set; }
[DisplayName("Full name")]
public string Name { get; set; }
[DisplayName("Age")]
public int Age { get; set; }
[DisplayName("Salary")]
public float Salary { get; set; }
[DisplayName("Department name")]
public string Department { get; set; }

}
}


​Add an "addHeader" method to "ExcelLib.cs" class. This method allows to add and style header of the table in excel file.
using ClosedXML.Excel;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
namespace ExcelGeneratingApp.Models
{
public class ExcelLib
{
// Default Constructor.
public ExcelLib() { }
// Method for adding Header and Title of the table containing List of object values.
public IXLWorksheet addHeader(XLWorkbook wb, List<Object> objs, string title,  string fontFamily = "Sakkal Majalla", string color = "#3498DB")
{
// Sheet initialisation.
var ws = wb.Worksheets.Add("nomDeLaListe").SetTabColor(XLColor.UaBlue);
// font choice.
ws.Style.Font.FontName = fontFamily;
ws.Style.Font.SetFontSize(13);
ws.Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
ws.Style.Alignment.WrapText = true;
Object obj = objs.FirstOrDefault();
// Add the model fields to the header of the excel file.
int totalOfFields = obj.GetType().GetProperties().Length; // number of fields in the object.
int numberOfFields = 0;
// Adding the title of table in excel file.
ws.Range(ws.Cell(4, 4), ws.Cell(4, totalOfFields + 3)).Merge().Value = title;
ws.Range(ws.Cell(4, 4), ws.Cell(4, totalOfFields + 3)).Merge().Style.Fill.BackgroundColor = XLColor.FromHtml(color); ;
ws.Range(ws.Cell(4, 4), ws.Cell(4, totalOfFields + 3)).Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
ws.Range(ws.Cell(4, 4), ws.Cell(4, totalOfFields + 3)).Style.Font.Bold = true;
ws.Range(ws.Cell(4, 4), ws.Cell(4, totalOfFields + 3)).Style.Font.FontColor = XLColor.WhiteSmoke;
ws.Range(ws.Cell(4, 4), ws.Cell(4, totalOfFields + 3)).Style.Font.FontSize = 18;
//Looping all propeties of the object.
foreach (var prop in obj.GetType().GetProperties())
{
        var displayNameAttribute = prop.GetCustomAttributes(typeof(DisplayNameAttribute), false);
        string displayName = prop.Name;
        if (displayNameAttribute.Count() != 0)
        {
            displayName = (displayNameAttribute[0] as DisplayNameAttribute).DisplayName;
        }
        numberOfFields++;
        ws.Cell(5, totalOfFields - numberOfFields + 4).Value = displayName;
        ws.Cell(5, totalOfFields - numberOfFields + 4).Style.Border.BottomBorder = XLBorderStyleValues.Thin;
        ws.Cell(5, totalOfFields - numberOfFields + 4).Style.Border.LeftBorder = XLBorderStyleValues.Thin;
        ws.Cell(5, totalOfFields - numberOfFields + 4).Style.Border.RightBorder = XLBorderStyleValues.Thin;
        ws.Cell(5, totalOfFields - numberOfFields + 4).Style.Border.TopBorder = XLBorderStyleValues.Thin;
        ws.Column(totalOfFields - numberOfFields + 4).Width = 30;
        ws.Column(totalOfFields - numberOfFields + 4).Style.Font.Bold = true;
}
ws.Range(ws.Cell(5, 4), ws.Cell(5, totalOfFields + 3)).SetAutoFilter();
return ws;
}
}
}


Then add "addBody" method to the "ExcelLib.cs" class.
This method allows to add the list of objects "objs" content to the table in excel file.
It merges the cells of the first column containing the same values.
public IXLWorksheet addBody(IXLWorksheet ws, List<Object> objs)
{
int numberOfFields = 0;
int numberOfRecords = 0;
Object obj = objs.FirstOrDefault();
int totalOfFields = obj.GetType().GetProperties().Length;
string previousValue = "";
int indexOfPreviousValue = 0;

foreach (var item in objs.ToList())
{
  numberOfFields = 0;
  Type myType = item.GetType();
  IList<PropertyInfo> props = new List<PropertyInfo>(myType.GetProperties());

  foreach (PropertyInfo prop in props)
  {
      object propValue = prop.GetValue(item, null);

      numberOfFields++;
      ws.Cell(6 + numberOfRecords, totalOfFields - numberOfFields + 4).Value = propValue;

      ws.Cell(6 + numberOfRecords, totalOfFields - numberOfFields + 4).Style.Font.Bold = true;

      ws.Cell(6 + numberOfRecords, totalOfFields - numberOfFields + 4).Style.Border.BottomBorder = XLBorderStyleValues.Thin;
      ws.Cell(6 + numberOfRecords, totalOfFields - numberOfFields + 4).Style.Border.LeftBorder = XLBorderStyleValues.Thin;
      ws.Cell(6 + numberOfRecords, totalOfFields - numberOfFields + 4).Style.Border.RightBorder = XLBorderStyleValues.Thin;
      ws.Cell(6 + numberOfRecords, totalOfFields - numberOfFields + 4).Style.Border.TopBorder = XLBorderStyleValues.Thin;

      if (numberOfFields == 1 && numberOfRecords == 0)
      {
          previousValue = propValue.ToString();
      }
      else
      {
          if (numberOfFields == 1)
          {
              if (previousValue == propValue.ToString())
              {
                  ws.Range(ws.Cell(6 + numberOfRecords - (1 + indexOfPreviousValue), totalOfFields - numberOfFields + 4), ws.Cell(6 + numberOfRecords, totalOfFields - numberOfFields + 4)).Merge().Value = propValue.ToString();

                  ws.Range(ws.Cell(6 + numberOfRecords - (1 + indexOfPreviousValue), totalOfFields - numberOfFields + 4), ws.Cell(6 + numberOfRecords, totalOfFields - numberOfFields + 4)).Merge().Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
                  ws.Range(ws.Cell(6 + numberOfRecords - (1 + indexOfPreviousValue), totalOfFields - numberOfFields + 4), ws.Cell(6 + numberOfRecords, totalOfFields - numberOfFields + 4)).Merge().Style.Alignment.Vertical = XLAlignmentVerticalValues.Center;
                  indexOfPreviousValue++;
              }
              else
              {
                  previousValue = propValue.ToString();
                  indexOfPreviousValue = 0;
              }
          }

      }


  }
  numberOfRecords++;
}

return ws;
}


Then add a "Generate" method for generating the excel file.
public void Generate(List<Object> objs, string title, string fontFamily = "Sakkal Majalla", string color = "#3498DB")
{
// Workbook creation.
using (XLWorkbook wb = new XLWorkbook())
{
        var ws = addHeader(wb, objs, title);
            ws = addBody(ws, objs);
            wb.SaveAs("C://TestExcelGen.xlsx");
}
}

Step 4
To test this method, we will add some code to the Home controller.
public ActionResult Index()
{
List<Employee> employees = new List<Employee>();
employees.Add(new Employee() { ID = 100 ,Name="PETER", Age=32,Salary=12000,Department="INFO"}) ;
employees.Add(new Employee() { ID = 200 ,Name="SCOTT", Age=24,Salary=10000,Department="CIVIL"}) ;
employees.Add(new Employee() { ID = 300 ,Name="ADAM", Age=20,Salary=11000,Department="INDUS"}) ;
employees.Add(new Employee() { ID = 400 ,Name="ETHAN", Age=21,Salary=9000,Department="INFO"}) ;
ExcelLib excel = new ExcelLib();

excel.Generate(employees.Cast<object>().ToList(), "List of employees");

return View();
}

The full ExcelLib.cs content:
using ClosedXML.Excel;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Reflection;

namespace ExcelGeneratingApp.Models
{
public class ExcelLib
{
// Default Constructor.
public ExcelLib() { }
// Method for adding Header and Title of the table containing List of object values.
public IXLWorksheet addHeader(XLWorkbook wb, List<Object> objs, string title,  string fontFamily = "Sakkal Majalla", string color = "#3498DB")
{
// Sheet initialisation.
var ws = wb.Worksheets.Add("nomDeLaListe").SetTabColor(XLColor.UaBlue);
// font choice.
ws.Style.Font.FontName = fontFamily;
ws.Style.Font.SetFontSize(13);
ws.Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
ws.Style.Alignment.WrapText = true;
Object obj = objs.FirstOrDefault();
// Add the model fields to the header of the excel file.
int totalOfFields = obj.GetType().GetProperties().Length; // number of fields in the object.
int numberOfFields = 0;
// Adding the title of table in excel file.
ws.Range(ws.Cell(4, 4), ws.Cell(4, totalOfFields + 3)).Merge().Value = title;
ws.Range(ws.Cell(4, 4), ws.Cell(4, totalOfFields + 3)).Merge().Style.Fill.BackgroundColor = XLColor.FromHtml(color); ;
ws.Range(ws.Cell(4, 4), ws.Cell(4, totalOfFields + 3)).Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
ws.Range(ws.Cell(4, 4), ws.Cell(4, totalOfFields + 3)).Style.Font.Bold = true;
ws.Range(ws.Cell(4, 4), ws.Cell(4, totalOfFields + 3)).Style.Font.FontColor = XLColor.WhiteSmoke;
ws.Range(ws.Cell(4, 4), ws.Cell(4, totalOfFields + 3)).Style.Font.FontSize = 18;
//Looping all propeties of the object.
foreach (var prop in obj.GetType().GetProperties())
{
        var displayNameAttribute = prop.GetCustomAttributes(typeof(DisplayNameAttribute), false);
        string displayName = prop.Name;
        if (displayNameAttribute.Count() != 0)
        {
            displayName = (displayNameAttribute[0] as DisplayNameAttribute).DisplayName;
        }
        numberOfFields++;
        ws.Cell(5, totalOfFields - numberOfFields + 4).Value = displayName;
        ws.Cell(5, totalOfFields - numberOfFields + 4).Style.Border.BottomBorder = XLBorderStyleValues.Thin;
        ws.Cell(5, totalOfFields - numberOfFields + 4).Style.Border.LeftBorder = XLBorderStyleValues.Thin;
        ws.Cell(5, totalOfFields - numberOfFields + 4).Style.Border.RightBorder = XLBorderStyleValues.Thin;
        ws.Cell(5, totalOfFields - numberOfFields + 4).Style.Border.TopBorder = XLBorderStyleValues.Thin;
        ws.Column(totalOfFields - numberOfFields + 4).Width = 30;
        ws.Column(totalOfFields - numberOfFields + 4).Style.Font.Bold = true;
}
ws.Range(ws.Cell(5, 4), ws.Cell(5, totalOfFields + 3)).SetAutoFilter();
return ws;
}
public IXLWorksheet addBody(IXLWorksheet ws, List<Object> objs)
{
int numberOfFields = 0;
int numberOfRecords = 0;
Object obj = objs.FirstOrDefault();
int totalOfFields = obj.GetType().GetProperties().Length;
string previousValue = "";
int indexOfPreviousValue = 0;

foreach (var item in objs.ToList())
{
    numberOfFields = 0;
    Type myType = item.GetType();
    IList<PropertyInfo> props = new List<PropertyInfo>(myType.GetProperties());

    foreach (PropertyInfo prop in props)
    {
        object propValue = prop.GetValue(item, null);
        numberOfFields++;
        ws.Cell(6 + numberOfRecords, totalOfFields - numberOfFields + 4).Value = propValue;
        ws.Cell(6 + numberOfRecords, totalOfFields - numberOfFields + 4).Style.Font.Bold = true;
        ws.Cell(6 + numberOfRecords, totalOfFields - numberOfFields + 4).Style.Border.BottomBorder = XLBorderStyleValues.Thin;
        ws.Cell(6 + numberOfRecords, totalOfFields - numberOfFields + 4).Style.Border.LeftBorder = XLBorderStyleValues.Thin;
        ws.Cell(6 + numberOfRecords, totalOfFields - numberOfFields + 4).Style.Border.RightBorder = XLBorderStyleValues.Thin;
        ws.Cell(6 + numberOfRecords, totalOfFields - numberOfFields + 4).Style.Border.TopBorder = XLBorderStyleValues.Thin;

        if (numberOfFields == 1 && numberOfRecords == 0)
        {
            previousValue = propValue.ToString();
        }
        else
        {
            if (numberOfFields == 1)
            {
                if (previousValue == propValue.ToString())
                {
                    ws.Range(ws.Cell(6 + numberOfRecords - (1 + indexOfPreviousValue), totalOfFields - numberOfFields + 4), ws.Cell(6 + numberOfRecords, totalOfFields - numberOfFields + 4)).Merge().Value = propValue.ToString();

                    ws.Range(ws.Cell(6 + numberOfRecords - (1 + indexOfPreviousValue), totalOfFields - numberOfFields + 4), ws.Cell(6 + numberOfRecords, totalOfFields - numberOfFields + 4)).Merge().Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
                    ws.Range(ws.Cell(6 + numberOfRecords - (1 + indexOfPreviousValue), totalOfFields - numberOfFields + 4), ws.Cell(6 + numberOfRecords, totalOfFields - numberOfFields + 4)).Merge().Style.Alignment.Vertical = XLAlignmentVerticalValues.Center;
                    indexOfPreviousValue++;
                }
                else
                {
                    previousValue = propValue.ToString();
                    indexOfPreviousValue = 0;
                }
            }
        }
    }
    numberOfRecords++;
}
return ws;
}
public void Generate(List<Object> objs, string title, string fontFamily = "Sakkal Majalla", string color = "#3498DB")
{
// Workbook creation.
using (XLWorkbook wb = new XLWorkbook())
{
        var ws = addHeader(wb, objs, title);
            ws = addBody(ws, objs);
            wb.SaveAs("C://TestExcelGen.xlsx");
}
}
}
}

NB: You can download all project source code from my github page.

Conclusion
I think the procedure is very clear with snapshots. If you have found any mistake in concept, please do comment. Your comments will make me perfect in the future.
Thanks for reading.

 



ASP.NET MVC Hosting - HostForLIFEASP.NET :: Pagination In MVC With Jquery DataTable

clock October 6, 2022 09:09 by author Peter

All of us are beginners & all of us face the performance issue while fetching huge data from the database. One of the solutions is that we can bring a small piece of data (how much data we require to show) and we can achieve with Jquery DataTable. By default Jquery DataTable will bring all the data from Backend and Bind into the Table, but we don't want all the records at one go.


For this, we can go with Server Side Pagination with Jquery DataTable

There are many articles on Server Side Pagination on the internet, But max of them used "context.Request.Form" for getting the DataTable Properties for eg: context.Request.Form["draw"], context.Request.Form["start"]. But most of the time it gets null and we struggle for getting the values
In this article, we can achieve the Server side pagination with object with Post methods

Let's Start with the Database, For this I'm using Northwind Sample Database, you can download this database from
https://github.com/microsoft/sql-server-samples/tree/master/samples/databases/northwind-pubs

Once you added the database in the SQL you will find the Employees table with 10-15 Records, for this article I have added 576 records

Now here is the stored procedure for getting employees data


In this SP we are passing 4 parameters  
CREATE procedure [dbo].[getEmployeeList]
(
@page INT = 0,
@size INT =10,
@sort nvarchar(50) ='EmployeeId asc',
@totalrow INT  ='50'
)
AS
BEGIN
DECLARE @offset INT
DECLARE @newsize INT
DECLARE @sql NVARCHAR(MAX)

IF(@page=0)
BEGIN
SET @offset = @page
SET @newsize = @size
END
ELSE
BEGIN
SET @offset = @page+1
SET @newsize = @size-1
END
SET NOCOUNT ON
SET @sql = '
WITH OrderedSet AS
(
SELECT *, ROW_NUMBER() OVER (ORDER BY ' + @sort + ') AS ''Index''
FROM [dbo].Employees
)
SELECT * FROM OrderedSet WHERE [Index] BETWEEN ' + CONVERT(NVARCHAR(12), @offset) + ' AND ' + CONVERT(NVARCHAR(12), (@offset + @newsize))
EXECUTE (@sql)
SET @totalrow = (SELECT COUNT(*) FROM Employees)
select @totalrow
END

In MVC c# I have added Pagination.cs class like below
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace ServerSidePagination.Models
{
public class Pagination
{
public DatatablePostData data { get; set; }
}
public class DatatablePostData
{
public int draw { get; set; }
public int start { get; set; }
public int length { get; set; }
public List<Column> columns { get; set; }
public Search search { get; set; }
public List<Order> order { get; set; }
}

public class Column
{
public string data { get; set; }
public string name { get; set; }
public string searchable { get; set; }
public string orderable { get; set; }
public Search search { get; set; }
}

public class Search
{
public string value { get; set; }
public string regex { get; set; }
}

public class Order
{
public int column { get; set; }
public string dir { get; set; }
}
public class DTResponse
{
public int recordsTotal { get; set; }
public int recordsFiltered { get; set; }
public string data { get; set; }
}
}

Controller with action method for View Page (Add View page for paginationExample method)
public ActionResult paginationExample()
{
return View();
}

Controller with action method like below for getting the Employees data
[HttpPost]
public JsonResult GetEmployeeData(Pagination pagination)
{
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter();
DataSet ds = new DataSet();
DTResponse DTResponse = new DTResponse();
try
{
using (SqlConnection con = new SqlConnection(connectionString))
{
    SqlCommand cmd = new SqlCommand();
    cmd.Connection = con;
    cmd.Parameters.Clear();
    cmd.CommandText = "getEmployeeList";
    cmd.Parameters.AddWithValue("@sort",
    pagination.data.columns[pagination.data.order[0].column].name == null ?
    "EmployeeId asc" : pagination.data.columns[pagination.data.order[0].column].name+" "+
        pagination.data.order[0].dir);
    cmd.Parameters.AddWithValue("@size", pagination.data.length);
    cmd.Parameters.AddWithValue("@page", pagination.data.start);
    cmd.Parameters.AddWithValue("@totalrow", pagination.data.length);
    // cmd.Parameters.AddWithValue("@P_Search", pagination.data.search.value);
    cmd.CommandType = System.Data.CommandType.StoredProcedure;
    sqlDataAdapter.SelectCommand = cmd;
    sqlDataAdapter.Fill(ds);

}
DTResponse.recordsTotal = ds.Tables[0].Rows.Count;
DTResponse.recordsFiltered = Convert.ToInt32(ds.Tables[1].Rows[0][0]);
DTResponse.data = JsonConvert.SerializeObject(ds.Tables[0]);
}
catch(Exception ex)
{

}
return Json(DTResponse, JsonRequestBehavior.AllowGet);
}

In View Side, add the Jquery Data Table References
<link href="https://cdn.datatables.net/1.12.1/css/jquery.dataTables.min.css" rel="stylesheet">
<script src="https://cdn.datatables.net/1.12.1/js/jquery.dataTables.min.js"></script>

cshtml Code
Here is the Ajax call for getting the Employees data with Server Side DataTable Properties
<h2>paginationExample</h2>
<script src="~/Scripts/jquery-3.4.1.js"></script>
<link href="https://cdn.datatables.net/1.12.1/css/jquery.dataTables.min.css" rel="stylesheet">
<script src="https://cdn.datatables.net/1.12.1/js/jquery.dataTables.min.js"></script>
<div id="tblUpdatePcInfo">

</div>
<script>
var table;
$(document).ready(function () {
GetAllEmployyesData();
})
function GetAllEmployyesData() {
var tablecontent = '<table id="tblPCInfo" class="table table-bordered table-striped display nowrap" style="width:100%"><thead><tr>\
<th>EmployeeID</th>\
<th><input type="checkbox" id="chkSelectAll" class="filled-in chk-col-success" title="Select All"/></th>\
<th class="LastName">LastName</th>\
<th>FirstName</th>\
<th>Title</th>\
<th>TitleOfCourtesy</th>\
<th>Address</th>\
<th>City</th>\
<th>PostalCode</th>\
<th>Country</th>\
<th>HomePhone</th>\
</tr></thead><tbody></tbody></table>';
$("#tblUpdatePcInfo").html(tablecontent);
table = $('#tblPCInfo').dataTable({
    clear: true,
    destroy: true,
    serverSide: true,
    pageLength: 50,
    lengthMenu: [[10, 25, 50, 100, 100000], [10, 25, 50, 100, "All"]],
    autoFill: false,
    "initComplete": function (settings, json) {
        $(this.api().table().container()).find('input').attr('autocomplete', 'off');
    },
    "ajax": {
        url: "/Home/GetEmployeeData",
        type: "POST",
        contentType: "application/json; charset=utf-8",
        data: function (d) {
            var data = { data: d };
            return JSON.stringify(data);
        },
        AutoWidth: false,
        "dataSrc": function (json) {
            var data = json;
            json.draw = data.draw;
            json.recordsTotal = data.recordsTotal;
            json.recordsFiltered = data.recordsFiltered;
            json.data = JSON.parse(data.data);
            return json.data;
        }
    },

    "columns": [
        {
            "data": "EmployeeID", "width": "10px", "orderable": false, "name": "EmployeeID"
        },
        {
            "data": "a", "width": "15px", "orderable": false, "name": "m.LicNo", "render": function (data, type, row, meta) {
                return '<div style="text-align:center;"><input type="checkbox" class="SelectedChk" id="' + row.LicNo + '" value="' + row.LicNo + '" class="filled-in chk-col-success" title="Select All"/></div>';
            },
            "searchable": false
        },
        {
            "data": "LastName", "name": "LastName", "searchable": false
        },
        { "data": "FirstName", "name": "FirstName", "searchable": false },
        { "data": "Title", "name": "Title", "searchable": false },
        { "data": "TitleOfCourtesy", "name": "TitleOfCourtesy", "searchable": false },
        { "data": "Address", "name": "Address", "searchable": false },
        { "data": "City", "name": "City", "searchable": false },
        {
            "data": "PostalCode", "name": "PostalCode", "searchable": false
        },
        { "data": "Country", "name": "Country", "searchable": false },
        { "data": "HomePhone", "name": "HomePhone", "searchable": false }
    ]
});
}
</script>


The Values of GetEmployeeData argument will be as follows

OUTPUT




ASP.NET MVC Hosting - HostForLIFEASP.NET :: Pass Data Across Views In .NET MVC

clock September 30, 2022 09:46 by author Peter

In this article, we will discuss something new: pass data across views. We will also summarize some common or important shared features for various vew variables.

Brief Summary of ViewData
We will start our discussion from ViewData, but most or all features are the same for other MVC View Variables. The ASP.NET Core also has the same features. So, we will discuss ViewData in the most, and have the last part to see the extension to other View variables.


Type of ViewData
We have discussed ViewData, ViewBag, TempData, Session type features. They are all the Type of Dictionary:

Where the difference between ViewBag and ViewData:

Besides ViewBag, all other View Variables need to be cast before using. We define a ViewData named "book": as type BookModel with data such as Id = 1:


When we retrieve data, we have to cast the data back to the data type. Otherwise, we will get an error message:

After casting:

Pass Data into _Layout.cshtml Page by ViewData
The _layout.cshtml is a shared page by other specific views. It belongs to no Controller or Action, or we can say it belongs to every Controller or Action when the related view is using _layout.cshtml. Therefore, we can pass data into Layout either from the Controller or Action view, that uses the _layout.cshtml, such as, if we have a Contact Us Action:

Or, we can define the ViewData from the Contact Us View:

Both ways will pass the data into Layout page:

Notes
1, We usually introduce the Layout into View by the code in the View as below:

2, in some cases, if we want to make the Layout page(s) dynamic, we can assign the layout to the view through Controller/Action:

3, A related important shared concept for MVC, _Viewstat.cshtml


Pass Data into _Layout.cshtml Page by Other View Variables
The same is true for other MVC View Variables, such as ViewBag, TempData, and absolutely Session variable:


Pass TempData to Layout:

Pass ViewData to Layout:

Pass ViewBag to Layout:

This article discussed using ASP.NET MVC ViewData to pass data into Layout View through either Controller or View.  The features are available or the same as other View Variables in ASP.NET MVC, and the same is true for ASP.NET Core MVC.



ASP.NET MVC Hosting - HostForLIFEASP.NET :: Type of Filters in MVC Application and Why They're Important

clock September 14, 2022 08:45 by author Peter

Introduction 
Let's discuss filters in ASP.NET MVC.

 
What are the Filters?
Filters in ASP.NET MVC are a way to implement cross-cutting logic, (for example, security and logging). Sometimes, we need to execute logic before or after executing an action. For such a scenario, ASP.NET MVC provides us with Filters.
 
ASP.Net MVC provides us with some built-in Filters:

    Output Cache- This action filter caches the output of a controller action for a specified amount of time.
    Handle Error- This action filter handles errors raised when a controller action executes.
    Authorize- This action filter enables you to restrict access to a particular user or role.

Asp.net MVC Filters are used to inject extra logic at the different levels of MVC Framework request processing. Filters provide a way for cross-cutting concerns (logging, authorization, and caching).
 
In this article, I will show you the different categories of filters that the MVC Framework supports, how to control their execution, and how to create and use filters. We can create our own custom filters. In every request, your action method in the controller will have to check if the user was right or authorized to perform the action and view its result.
 
The ASP.NET MVC Framework supports four different types of filters. Authentication Filters are introduced with ASP.NET MVC 5. Each allows you to introduce logic at different points during the request processing
 

1. Authorization filters
The AuthorizeAttribute and RequireHttpsAttribute are examples of Authorization Filters. Authorization Filters are responsible for checking User Access; these implement the IAuthorizationFilterinterface in the framework. These filters used to implement authentication and authorization for controller actions. For example, the Authorize filter is an example of an Authorization filter.
 
2. Action Filters
The Action Filter is an attribute that you can apply to a controller action or an entire controller. This filter will be called before and after the action starts executing and after the action has executed.
 
Action filters implement the IActionFilter interface that has two methods OnActionExecuting andOnActionExecuted. OnActionExecuting runs before the Action and gives an opportunity to cancel the Action call. These filters contain logic that is executed before and after a controller action executes, you can use an action filter, for instance, to modify the view data that a controller action returns.
 
3. Result Filters
The OutputCacheAttribute class is an example of Result Filters. These implement the IResultFilter interface which like the IActionFilter has OnResultExecuting and OnResultExecuted. These filters contain logic that is executed before and after a view result is executed. Like if you want to modify a view result right before the view is rendered to the browser.
 
4. ExceptionFilters
 
The HandleErrorAttribute class is an example of ExceptionFilters. These implement the IExceptionFilter interface and they execute if there are any unhandled exceptions thrown during the execution pipeline. These filters can be used as an exception filter to handle errors raised by either your controller actions or controller action results.
 
Summary
In this article, we learned about the Type of filters in MVC Application and why they're important.
Thanks for reading



ASP.NET MVC 6 Hosting - HostForLIFEASP.NET :: Data Sharing Techniques In MVC

clock August 29, 2022 08:55 by author Peter

1) View Data

ViewData is a built-in object of the "ViewDataDictionary" class.
ViewData stores the data in key-value pairs

Example
public IActionResult Index() {
    ViewData["Name"] = "MVC";
    return View();
}


Output

2) View Bag
ViewBag is also used for sending Data from the controller to View.
ViewBag is developed based on Dynamic Typing.
No need to perform Type Casting
Use key as property

Example
public IActionResult ViewBagIndex() {
    ViewBag.Name = "MVC";
    return View();
}


Output


3) Temp Data
TempData is used to transfer the aata from one Action to Another Action at the time of redirection
TempData is an object of the "TempDataDictionary" class

Example
public ActionResult TempDataIndex() {
    TempData["Name"] = "MVC";
    return View();
}

Output

Please do leave a comment if you find it useful.



ASP.NET MVC 6 Hosting - HostForLIFEASP.NET :: Pass Dynamically Added HTML Table Records List To Controller In ASP.NET MVC

clock August 23, 2022 07:37 by author Peter

Many times we need to post a list of records to controller instead of a single record to controller such as dynamically added html table records etc . Also I have learned on many forum posts regarding the problem in posting a list of records to controller, as many are saying while posting list of records we are getting only one record at controller instead of list of records . So by considering this requirement I have decided to write this article . Now let's learn step by step which helps beginners to learn how to get list of records into ASP.NET MVC controller .
 
Scenario
Let's consider we have a requirement in which a single user can add multiple orders of products at a time instead of  ordering one by one. So in this scenario we need to create one single view from a complex model that is from multiple models where one model can be used to hold customer information and the second model used to hold the list of records .

So let's demonstrate the preceding scenario by creating one simple ASP.NET MVC application

Step 1: Create an MVC Application.
Now let us start with a step by step approach from the creation of a simple MVC application as in the following:

    "Start", then "All Programs" and select "Microsoft Visual Studio 2015".

    "File", then "New" and click "Project", then select "ASP.NET Web Application Template", then provide the Project a name as you wish and click OK. After clicking, the following window will appear:

Step 2: Create Model Class
Now let us create the model class file named OrderModel.cs by right clicking on model folder as in the following screenshot:

Note:
It is not mandatory that Model class should be in Models folder, it is just for better readability; you can create this class anywhere in the solution explorer. This can be done by creating different folder names or without folder name or in a separate class library.

OrderModel.cs class file code snippet:
    /// <summary>  
       /// To hold order details  
       /// </summary>  
      public class OrderModel  
       {  
           public string ProductCode { get; set; }  
           public string ProductName { get; set; }  
           public Int16 Qty { get; set; }  
           public double Price { get; set; }  
           public double TotalAmount { get; set; }  
       }  
      public class OrderDetail  
       {  
           /// <summary>  
           /// To hold list of orders  
           /// </summary>  
           public List<OrderModel> OrderDetails { get; set; }  
      
       }


 Step 3: Add Controller Class.
Now let us add the MVC 5 controller as in the following screenshot:


After clicking on Add button it will show the window. Specify the Controller name as Order with suffix Controller.

Note:
The controller name must be having suffix as 'Controller' after specifying the name of controller. Now modify the default code in OrderController.cs class file to bind HTML table in view from strongly typed model class with list of records and getting those list of records into controller, after modifying code will look like as follows,

OrderController.cs
      public class OrderController : Controller  
        {  
            /// <summary>  
            /// Get list of records with View     
            /// </summary>  
            /// <returns></returns>  
            public ActionResult PlaceOrder()  
            {  
                List<OrderModel> objOrder = new List<OrderModel>()  
                {  
     new OrderModel {ProductCode="AOO1",ProductName="Windows Mobile",Qty=1,Price=45550.00,TotalAmount=45550.00 },  
    new OrderModel {ProductCode="A002",ProductName="Laptop",Qty=1,Price=67000.00,TotalAmount=67000.00 },  
    new OrderModel {ProductCode="A003",ProductName="LCD Television",Qty=2,Price=15000.00,TotalAmount=30000.00 },  
    new OrderModel {ProductCode="A004",ProductName="CD Player",Qty=4,Price=10000.00,TotalAmount=40000.00 }  
                };  
      
                OrderDetail ObjOrderDetails = new OrderDetail();  
                ObjOrderDetails.OrderDetails = objOrder;  
                return View(ObjOrderDetails);  
            }  
            /// <summary>  
            /// Get list of records from view  
            /// </summary>  
            /// <param name="Order"></param>  
            /// <returns></returns>  
            [HttpPost]  
            public ActionResult PlaceOrder(OrderDetail Order)  
            {  
      
      
                return View();  
            }  
        }


Step 4:
Creating strongly typed view named PlaceOrder using OrderDetail class. Right click on View folder of created application and choose add view, select OrderDetail model class and scaffolding template List   as,


Click on Add button then it will create the view named PlaceOrder , Now open the PlaceOrder.cshtml view, Then some default code you will see which is generated by MVC scaffolding template, Now modify default code to make as per our requirements, After modifying the code it will look like the following,

PlaceOrder.cshtml
@model GetHTMLTableRecordsInMVC.Models.OrderDetail  
@{  
    ViewBag.Title = "www.cpmpilemode.com";  
}  
<hr />  
@using (Html.BeginForm())  
{  
    @Html.AntiForgeryToken()  
 
    <div class="form-horizontal">  
        <div class="form-group">  
            <div class="col-md-offset-2 col-md-10 text-right">  
                 <input type="button" value="Add Product" class="btn btn-primary" />  
            </div>  
        </div>  
        <div class="form-group">  
            <div class="col-md-12">  
                <table class="table table-condensed table-hover">  
                    <tr>  
                        <th>  
                            Product Code  
                        </th>  
                        <th>  
                            Product Name  
                        </th>  
                        <th>  
                            Quantity  
                        </th>  
                        <th>  
                            Price  
                        </th>  
                        <th>  
                            Total Amount  
                        </th>  
                    </tr>  
                    @{  
                        //To make unique Id  
                        int i = 0;  
                        foreach (var item in Model.OrderDetails.ToList())  
                        {  
 
                            <tr>  
                                <td>  
 
 
                                    @Html.EditorFor(o => o.OrderDetails[i].ProductCode, new { @id = "ItemCode_" + i })  
                                </td>  
                                <td>  
                                    @Html.EditorFor(o => o.OrderDetails[i].ProductName, new { @id = "ProductName_" + i })  
                                </td>  
                                <td>  
                                    @Html.EditorFor(o => o.OrderDetails[i].Qty, new { @id = "Qty_" + i })  
                                </td>  
                                <td>  
                                    @Html.EditorFor(o => o.OrderDetails[i].Price, new { @id = "Price_" + i })  
                                </td>  
                                <td>  
                                    @Html.EditorFor(o => o.OrderDetails[i].TotalAmount, new { @id = "Price_" + i })  
                                </td>  
 
                            </tr>  
                            i++;  
                        }  
                    }  
                </table>  
            </div>  
        </div>  
        <hr />  
        <div class="form-group">  
            <div class="col-md-offset-2 col-md-10 text-center">  
                <input type="submit" value="Place Order" class="btn btn-primary" />  
            </div>  
        </div>  
    </div>  
 }


Common issues
While binding list of records your control Id's must be unique , otherwise same first record will repeat in all lists. So to avoid this we need to maintain  unique id's for control . As we have maintained in preceding view manually by using incremental i counter and model properties .

Now after adding the Model, View and controller into our project. The solution explorer will look like as follows,


Now we have done all coding to upload files . Step 5 : Now run the application. After running the application initial screen will look like as follows,


In preceding table we are adding orders (records) dynamically. Put break point on PlaceOrder action result method and click on Place Order button. Now the reference variable Order of OrderDetail class will show the four records in debug mode as,

In the preceding image you can see that four records list count which is coming from view because we have added four records into the table . Now Expand the OrderDetails node it will show the following records,

I hope from all preceding examples we have learned how to pass dynamically added HTML table records list to controller in ASP.NET MVC.

Note:

    Download the Zip file of the sample application for a better understanding.
    Add product button is just for scenario purpose , In next article I will explain how to add dynamic records into html table .
    Since this is a demo, it might not be using proper standards, so improve it depending on your skills.

Summary

I hope this article is useful for all readers. If you have any suggestions please contact me.



ASP.NET MVC Hosting - HostForLIFEASP.NET :: View Injection In ASP.NET Core MVC

clock August 16, 2022 09:15 by author Peter

View injection is the most useful feature introduced in ASP.NET Core. Using ASP.NET Core inbuilt dependency injection container, we can easily inject dependencies in Controllers, Filters, and Views. In this post, I am going to show how to inject dependencies using inject keyword in the View.

Previously, to retrieve the data in View, we needed to pass it from the Controller using Controller properties, like ViewBag, ViewData or model properties. In ASP.NET Core MVC, things are quite smooth by the usage of Inject directive. Inject helps with injecting the dependencies directly to the View and retrieving the data.

Setup project
In Visual Studio, create a new project (File > New > Project), and select ASP.NET Core Web Application (.NET Core).

Enter a name for the application and click OK. Select Web Application to generate the default ASP.NET Core MVC project.

Visual Studio will automatically generate ASP.NET Core MVC project structure and display a welcome screen.

Add Services
Add a new folder "Models" and add FruitServices class in it. Now, add a method GetFruits() which returns List<string>().

    public class FruitServices  
    {  
        public List<string> GetFruits()  
        {  
            return new List<string>() { "Mango", "Apple", "Apricot", "Banana", "Grapes" };  
        }  
    }  


Inject in View
We can inject a service into a View using the @inject directive. You can think of @inject as adding a property to your View, and populating the property using DI.
 
The basic syntax for View Injection is:
    @inject <service> <name>  

    @inject is the directive used to inject dependencies
    <service> is service class.
    <name> is the service injection name by which we can access service methods.


In our example, we are going to inject FruitServices and give service injection name fruitList.
    @inject MVCCoreExample.Models.FruitServices fruitList  
      
    <h3>Fruit List</h3>  
    <ul>  
        @foreach (var name in fruitList.GetFruits())  
        {  
            <li>@name</li>  
        }  
    </ul>  


This View displays a list of fruits which are populated from the injected FruitServices. Using GetFruit() method, we can retrieve a list of fruits.
 
Let's run it without registering FruitServices in DI container.

When we run the app, it will throw an invalid operation exception "No service for type 'MVCCoreExample.Modes.FruitServices' has been registered". This error occurred because we didn't register FruitServices in a dependency injection container.
 
Let's register it first and try again!
Register Service
Open startup.cs class and register service for dependency injection in ConfigureServices method. You can register your own application services, using AddTransient method. FruitServices will be instantiated by the container and used to fulfill such requests.

    public void ConfigureServices(IServiceCollection services)  
    {  
        // Add framework services.  
        services.AddMvc();  
        services.AddTransient<FruitServices>();  
    }  

Run it!
Here it is! The sample displays the data from the service injected in View.

 

Injecting dependencies directly into MVC View can make things a bit easier. In this post, I have shown a simple View Injection sample to understand the use of Inject directive. View injection can be useful for populating UI elements, like selection list, radio buttons etc. This will increase code re-usability and keep your Controller clean by minimizing the amount of code required on Controllers.



ASP.NET MVC Hosting - HostForLIFEASP.NET :: Web API CRUD Operations And Consume Service In ASP.NET MVC Application

clock August 9, 2022 09:00 by author Peter

This article will give you an understanding of the what and the why of Web API and will demonstrate a CRUD operation with a simple example using Entity Framework and consuming the created service into ASP.NET MVC application.

 
The flow of the article

    What is Web API
    Why Web API
    Real time example of WEBAPI
    Steps to Create table, Web API Service, and MVC application to consume the service.

        Create a table in SQL Server.
        Create Data Access Layer in Visual Studio to access the data and perform DB operation.
        Create a Web API project.
        Create MVC Application to consume Web API Service. Project created in step II, III, and IV belonging to one same solution
        Set Project Startup Order

    Output Screens
    Conclusion

Web API
    Web API provides service that can be consumed by a broad range of clients like mobile, tablet, desktop, etc.
    The response can be in any format, like XML, JSON (widely used), etc.
    It supports MVC features, like controller, action, routing, etc.
    Supports CRUD operation. CRUD stands for Create, Read, Update and Delete. It works on HTTP verbs like HttpPost to Create, HttpGet to Read, HttpPut to Update and HttpDelete to Delete.

Why Web API?


Without Web API, the server will have one application to handle the XML request and another application to handle the JSON request, i.e., for each request type, the server will have one application. But with Web API, the server can respond to any request type using a single application. Small end devices like mobile, tablet are capable of handling only the JSON data. So, the Web API has huge scope to give space in the real world.
 
A real-time example of WebAPI

    Weather forecasting
    Movie, Bus, Flight booking

There can be one service provider who offers the service and many consumers to avail this service.
 
Step 1 - Create a table in SQL Server
We will create a table to perform CRUD operation with Web API. The table script is given below.

    CREATE TABLE [dbo].[Product](  
        [ProductId] [int] PRIMARY KEY IDENTITY(1,1) NOT NULL,  
        [ProductName] [nvarchar](100) NULL,  
        [Quantity] [int] NULL,  
        [Price] [int] NULL)  


Step 2 - Create Class Library Project
    New Project -> Visual C# -> Windows -> Class Library Project and name it as DataAccessLayer.
    Right-click on DataAccessLayer project->Add->New Item->Data-> ADO.NET Entity Data Model and name it as ShowRoomEF.
    Choose EF designer from database in next step.
    Add the table created in step1 into Entity Framework.



Create a class called DAL.cs in this project to access the data from DB by Web API service. The code is given below.

DAL.cs
    public static class DAL  
    {  
        static ShowroomEntities DbContext;  
        static DAL()  
        {  
            DbContext = new ShowroomEntities();  
        }  
        public static List<Product> GetAllProducts()  
        {  
            return DbContext.Products.ToList();  
        }  
        public static Product GetProduct(int productId)  
        {  
            return DbContext.Products.Where(p => p.ProductId ==  productId).FirstOrDefault();  
        }  
        public static bool InsertProduct(Product productItem)  
        {  
            bool status;  
            try  
            {  
                DbContext.Products.Add(productItem);  
                DbContext.SaveChanges();  
                status = true;  
            }  
            catch (Exception)  
            {  
                status = false;  
            }  
            return status;  
        }  
        public static bool UpdateProduct(Product productItem)  
        {  
            bool status;  
            try  
            {  
                Product prodItem = DbContext.Products.Where(p => p.ProductId == productItem.ProductId).FirstOrDefault();  
                if (prodItem != null)  
                {  
                    prodItem.ProductName = productItem.ProductName;  
                    prodItem.Quantity = productItem.Quantity;  
                    prodItem.Price = productItem.Price;  
                    DbContext.SaveChanges();  
                }  
                status = true;  
            }  
            catch (Exception)  
            {  
                status = false;  
            }  
            return status;  
        }  
        public static bool DeleteProduct(int id)  
        {  
            bool status;  
            try  
            {  
                Product prodItem = DbContext.Products.Where(p => p.ProductId == id).FirstOrDefault();  
                if (prodItem != null)  
                {  
                    DbContext.Products.Remove(prodItem);  
                    DbContext.SaveChanges();  
                }  
                status = true;  
            }  
            catch (Exception)  
            {  
                status = false;  
            }  
            return status;  
        }  
    }  

Step 3 - Create Empty Web API Project
 
Navigate as given
Select New Project -> Visual C# -> Web -> ASP.NET Web Application and enter your application and solution name.

Select the empty template from options and check Web API checkbox and click OK.

The solution will be created as below.



    In App_Start -> WebApiConfig.cs file make sure routeTemplate as given below because by default, the route will not have {action}.

In WebApiConfig.cs

    public static void Register(HttpConfiguration config)  
           {  
               // Web API configuration and services  
      
               // Web API routes  
               config.MapHttpAttributeRoutes();  
      
               config.Routes.MapHttpRoute(  
                   name: "DefaultApi",  
                   routeTemplate: "api/{controller}/{action}/{id}",  
                   defaults: new { id = RouteParameter.Optional }  
               );  
     }

    Add Reference to DataAccessLayer project.
    Add the below DLL in references.

        EntityFramework
        SqlServer
        Net.Http
        Net.Http.Formatting

    Install Entity Framework from ‘NuGet Package Manager’.
    Create a Model class for the product as below.


Product.cs
    namespace WebApiService.Models  
    {  
        public class Product  
        {  
            public int ProductId { get; set; }  
            public string ProductName { get; set; }  
            public Nullable<int> Quantity { get; set; }  
            public Nullable<int> Price { get; set; }  
        }  
    }  

Copy the connection string from DataAccessLayer -> web.config and paste it in WebApiService -> web.config.
    <connectionStrings>  
        <add name="ShowroomEntities" connectionString="metadata=res://*/ShowRoomEF.csdl|res://*/ShowRoomEF.ssdl|res://*/ShowRoomEF.msl;provider=System.Data.SqlClient;provider connection string="data source=MYSYSTEM\SQLEXPRESS;initial catalog=Showroom;user id=sa;password=xxxxx;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />  
      </connectionStrings>  


Add Showroom Controller and make class to inherit from ApiController.
 
ShowroomController.cs

Showroom Controller takes care of Inserting, Retrieving, Updating and Deleting the data in the database. Request comes to this controller from the consuming application.
    public class ShowroomController: ApiController {  
        // GET: Showroom  
        [HttpGet]  
        public JsonResult < List < Models.Product >> GetAllProducts() {  
                EntityMapper < DataAccessLayer.Product, Models.Product > mapObj = new EntityMapper < DataAccessLayer.Product, Models.Product > ();  
                List < DataAccessLayer.Product > prodList = DAL.GetAllProducts();  
                List < Models.Product > products = new List < Models.Product > ();  
                var config = new MapperConfiguration(cfg => cfg.CreateMap < Product, Models.Product > ());  
                var mapper = new Mapper(config);  
                foreach(var item in prodList) {  
                    products.Add(mapper.Map < Models.Product > (item));  
                }  
                return Json < List < Models.Product >> (products);  
            }  
            [HttpGet]  
        public JsonResult < Models.Product > GetProduct(int id) {  
                EntityMapper < DataAccessLayer.Product, Models.Product > mapObj = new EntityMapper < DataAccessLayer.Product, Models.Product > ();  
                DataAccessLayer.Product dalProduct = DAL.GetProduct(id);  
                Models.Product products = new Models.Product();  
                var config = new MapperConfiguration(cfg => cfg.CreateMap < Product, Models.Product > ());  
                var mapper = new Mapper(config);  
                products = mapper.Map < Models.Product > (dalProduct);  
                return Json < Models.Product > (products);  
            }  
            [HttpPost]  
        public bool InsertProduct(Models.Product product) {  
                bool status = false;  
                if (ModelState.IsValid) {  
                    EntityMapper < Models.Product, DataAccessLayer.Product > mapObj = new EntityMapper < Models.Product, DataAccessLayer.Product > ();  
                    DataAccessLayer.Product productObj = new DataAccessLayer.Product();  
                    var config = new MapperConfiguration(cfg => cfg.CreateMap < Models.Product, Product > ());  
                    var mapper = new Mapper(config);  
                    productObj = mapper.Map < Product > (product);  
                    status = DAL.InsertProduct(productObj);  
                }  
                return status;  
            }  
            [HttpPut]  
        public bool UpdateProduct(Models.Product product) {  
                EntityMapper < Models.Product, DataAccessLayer.Product > mapObj = new EntityMapper < Models.Product, DataAccessLayer.Product > ();  
                DataAccessLayer.Product productObj = new DataAccessLayer.Product();  
                var config = new MapperConfiguration(cfg => cfg.CreateMap < Models.Product, Product > ());  
                var mapper = new Mapper(config);  
                productObj = mapper.Map < Product > (product);  
                var status = DAL.UpdateProduct(productObj);  
                return status;  
            }  
            [HttpDelete]  
        public bool DeleteProduct(int id) {  
            var status = DAL.DeleteProduct(id);  
            return status;  
        }  
    }  


Check your service
Execute your service created just now by running the below URL in the browser and change the port number accordingly.
http://localhost:52956/api/showroom/getallproducts
 

Service Output

Note
Attached WebApiServiceProvider.zip solution.
since solution size exceeds permitted one, have removed 'packages' folder content of 'WebApiServiceProvider' and kept in package_content_1.zip and package_content_2.zip.
 
Kindly don't forget to unzip package_content_1.zip and package_content_2.zip and keep their contents in 'WebApiServiceProvider\packages' folder. Also make changes to connection strings accordingly in both the solution.
 
Step 4 – Consuming Web Api Service In MVC Application
    Create Empty MVC project as below.



Create Product model class as created in WebApiService project.
Create ServiceRepository.cs in Repository folder to consume the web api service and create ServiceUrl as key and as a value in web.config (port number changes according to the server).
    <add key="ServiceUrl" value="http://localhost:52956/"></add>  

Add the below DLL in the references.
    Net
    Net.Http
    Net.Http.Formatting

ServiceRepository.cs
Service Repository is created to act as a reusable module for requesting, posting, updating and deleting data in WebAPI. This is used by any action method in the Controller which is created in next step and avoids duplication of this code.

public class ServiceRepository  
{  
       public HttpClient Client { get; set; }  
       public ServiceRepository()  
       {  
           Client = new HttpClient();  
           Client.BaseAddress = new Uri(ConfigurationManager.AppSettings["ServiceUrl"].ToString());  
       }  
       public HttpResponseMessage GetResponse(string url)  
       {  
           return Client.GetAsync(url).Result;  
       }  
       public HttpResponseMessage PutResponse(string url,object model)  
       {  
           return Client.PutAsJsonAsync(url, model).Result;  
       }  
       public HttpResponseMessage PostResponse(string url, object model)  
       {  
           return Client.PostAsJsonAsync(url,model).Result;  
       }  
       public HttpResponseMessage DeleteResponse(string url)  
       {  
           return Client.DeleteAsync(url).Result;  
       }  
}


Create a Controller to handle a request for different action method and navigate to the corresponding view.

ProductController.cs
Product Controller in MVC application is created to handle the request received from the user action and to serve the response accordingly. Code for product controller is given below.
public class ProductController : Controller  
{  
    // GET: Product  
    public ActionResult GetAllProducts()  
    {  
        try  
        {  
            ServiceRepository serviceObj = new ServiceRepository();  
            HttpResponseMessage response = serviceObj.GetResponse("api/showroom/getallproducts");  
            response.EnsureSuccessStatusCode();  
            List<Models.Product> products = response.Content.ReadAsAsync<List<Models.Product>>().Result;  
            ViewBag.Title = "All Products";  
            return View(products);  
        }  
        catch (Exception)  
        {  
            throw;  
        }  
    }  
    //[HttpGet]  
    public ActionResult EditProduct(int id)  
    {  
        ServiceRepository serviceObj = new ServiceRepository();  
        HttpResponseMessage response = serviceObj.GetResponse("api/showroom/GetProduct?id=" + id.ToString());  
        response.EnsureSuccessStatusCode();  
        Models.Product products = response.Content.ReadAsAsync<Models.Product>().Result;  
        ViewBag.Title = "All Products";  
        return View(products);  
    }  
    //[HttpPost]  
    public ActionResult Update(Models.Product product)  
    {  
        ServiceRepository serviceObj = new ServiceRepository();  
        HttpResponseMessage response = serviceObj.PutResponse("api/showroom/UpdateProduct", product);  
        response.EnsureSuccessStatusCode();  
        return RedirectToAction("GetAllProducts");  
    }  
    public ActionResult Details(int id)  
    {  
        ServiceRepository serviceObj = new ServiceRepository();  
        HttpResponseMessage response = serviceObj.GetResponse("api/showroom/GetProduct?id=" + id.ToString());  
        response.EnsureSuccessStatusCode();  
        Models.Product products = response.Content.ReadAsAsync<Models.Product>().Result;  
        ViewBag.Title = "All Products";  
        return View(products);  
    }  
    [HttpGet]  
    public ActionResult Create()  
    {  
        return View();  
    }  
    [HttpPost]  
    public ActionResult Create(Models.Product product)  
    {  
        ServiceRepository serviceObj = new ServiceRepository();  
        HttpResponseMessage response = serviceObj.PostResponse("api/showroom/InsertProduct", product);  
        response.EnsureSuccessStatusCode();  
        return RedirectToAction("GetAllProducts");  
    }  
    public ActionResult Delete(int id)  
    {  
        ServiceRepository serviceObj = new ServiceRepository();  
        HttpResponseMessage response = serviceObj.DeleteResponse("api/showroom/DeleteProduct?id=" + id.ToString());  
        response.EnsureSuccessStatusCode();  
        return RedirectToAction("GetAllProducts");  
    }  
}


Views are created in ConsumeWebApi MVC application to consume the service.

GetAllProducts.cshtml
.cshtml represents Views (UI) and this View displays all the products available which are received from API call in the corresponding method.

@model IEnumerable<ConsumeWebApi.Models.Product>  
 
@{  
    ViewBag.Title = "GetAllProducts";  
}  
 
<h2>GetAllProducts</h2>  
 
<p>  
    @Html.ActionLink("Create New", "Create")  
</p>  
<table class="table">  
    <tr>  
        <th>  
            @Html.DisplayNameFor(model => model.ProductName)  
        </th>  
        <th>  
            @Html.DisplayNameFor(model => model.Quantity)  
        </th>  
        <th>  
            @Html.DisplayNameFor(model => model.Price)  
        </th>  
        <th></th>  
    </tr>  
 
@foreach (var item in Model) {  
    <tr>  
        <td>  
            @Html.DisplayFor(modelItem => item.ProductName)  
        </td>  
        <td>  
            @Html.DisplayFor(modelItem => item.Quantity)  
        </td>  
        <td>  
            @Html.DisplayFor(modelItem => item.Price)  
        </td>  
        <td>  
            @Html.ActionLink("Edit", "EditProduct", new { id = item.ProductId, name= item.ProductName, quantity=item.Quantity, prod = item }) |  
            @Html.ActionLink("Details", "Details", new { id=item.ProductId }) |  
            @Html.ActionLink("Delete", "Delete", new { id=item.ProductId })  
        </td>  
    </tr>  
}  
 
</table>


Create.cshtml
This View allows the user to create a product and insert into the database through WebAPI call which is done in corresponding action method.
@model ConsumeWebApi.Models.Product  
 
@{  
    ViewBag.Title = "Create";  
}  
 
<h2>Create</h2>  
 
@using (Html.BeginForm())   
{  
    @Html.AntiForgeryToken()  
      
    <div class="form-horizontal">  
        <h4>Product</h4>  
        <hr />  
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })  
        <div class="form-group">  
            @Html.LabelFor(model => model.ProductName, htmlAttributes: new { @class = "control-label col-md-2" })  
            <div class="col-md-10">  
                @Html.EditorFor(model => model.ProductName, new { htmlAttributes = new { @class = "form-control" } })  
                @Html.ValidationMessageFor(model => model.ProductName, "", new { @class = "text-danger" })  
            </div>  
        </div>  
 
        <div class="form-group">  
            @Html.LabelFor(model => model.Quantity, htmlAttributes: new { @class = "control-label col-md-2" })  
            <div class="col-md-10">  
                @Html.EditorFor(model => model.Quantity, new { htmlAttributes = new { @class = "form-control" } })  
                @Html.ValidationMessageFor(model => model.Quantity, "", new { @class = "text-danger" })  
            </div>  
        </div>  
 
        <div class="form-group">  
            @Html.LabelFor(model => model.Price, htmlAttributes: new { @class = "control-label col-md-2" })  
            <div class="col-md-10">  
                @Html.EditorFor(model => model.Price, new { htmlAttributes = new { @class = "form-control" } })  
                @Html.ValidationMessageFor(model => model.Price, "", new { @class = "text-danger" })  
            </div>  
        </div>  
 
        <div class="form-group">  
            <div class="col-md-offset-2 col-md-10">  
                <input type="submit" value="Create" class="btn btn-default" />  
            </div>  
        </div>  
    </div>  
}  
 
<div>  
    @Html.ActionLink("Back to List", "GetAllProducts")  
</div>  

Details.cshtml
This View allows the user to see the particular product through WebAPI call which is done in the corresponding action method.
@model ConsumeWebApi.Models.Product  
 
@{  
    ViewBag.Title = "Detail";  
}  
 
<h2>Detail</h2>  
 
<div>  
    <h4>Product</h4>  
    <hr />  
    <dl class="dl-horizontal">  
        <dt>  
            @Html.DisplayNameFor(model => model.ProductName)  
        </dt>  
 
        <dd>  
            @Html.DisplayFor(model => model.ProductName)  
        </dd>  
 
        <dt>  
            @Html.DisplayNameFor(model => model.Quantity)  
        </dt>  
 
        <dd>  
            @Html.DisplayFor(model => model.Quantity)  
        </dd>  
 
        <dt>  
            @Html.DisplayNameFor(model => model.Price)  
        </dt>  
 
        <dd>  
            @Html.DisplayFor(model => model.Price)  
        </dd>  
 
    </dl>  
</div>  
<p>  
    @Html.ActionLink("Edit", "EditProduct", new { id = Model.ProductId }) |  
    @Html.ActionLink("Back to List", "GetAllProducts")  
</p>  


EditProduct.cshtml
This View allows the user to edit product and update database through WebAPI call which is done in the corresponding action method.
@model ConsumeWebApi.Models.Product  
 
@{  
    ViewBag.Title = "EditProduct";  
}  
 
<h2>EditProduct</h2>  
 
 
@using (Html.BeginForm("Update", "Product", FormMethod.Post))  
{  
    @Html.AntiForgeryToken()  
 
    <div class="form-horizontal">  
        <h4>Product</h4>  
        <hr />  
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })  
        @Html.HiddenFor(model => model.ProductId)  
 
        <div class="form-group">  
            @Html.LabelFor(model => model.ProductName, htmlAttributes: new { @class = "control-label col-md-2" })  
            <div class="col-md-10">  
                @Html.EditorFor(model => model.ProductName, new { htmlAttributes = new { @class = "form-control" } })  
                @Html.ValidationMessageFor(model => model.ProductName, "", new { @class = "text-danger" })  
            </div>  
        </div>  
 
        <div class="form-group">  
            @Html.LabelFor(model => model.Quantity, htmlAttributes: new { @class = "control-label col-md-2" })  
            <div class="col-md-10">  
                @Html.EditorFor(model => model.Quantity, new { htmlAttributes = new { @class = "form-control" } })  
                @Html.ValidationMessageFor(model => model.Quantity, "", new { @class = "text-danger" })  
            </div>  
        </div>  
 
        <div class="form-group">  
            @Html.LabelFor(model => model.Price, htmlAttributes: new { @class = "control-label col-md-2" })  
            <div class="col-md-10">  
                @Html.EditorFor(model => model.Price, new { htmlAttributes = new { @class = "form-control" } })  
                @Html.ValidationMessageFor(model => model.Price, "", new { @class = "text-danger" })  
            </div>  
        </div>  
 
 
        <div class="form-group"><div class="col-md-offset-2 col-md-10">  
                <input type="submit" value="Save" class="btn btn-default" />  
            </div>  
        </div>  
    </div>  
 
}  
 
<div>  
    @Html.ActionLink("Back to List", "GetAllProducts")  
</div>  


Step 5 – Set Project Startup Order

This step is necessary and has to be set up because this solution needs WebApiService application to keep running and serve the request. ConsumeWebAPI application will create a request to WebApiService and receive a response back.
So, in order to make two projects to keep up and running, this step is performed.
Whereas if WebApiService is hosted in IIS, then only one project which consumes the service can be started, i.e., MVC or postman.


Output Screens

    Get All Products View.

Create Product View.


Edit Product View.


Detailed View of a product.


Product table data in Product table of SQL Database.

Web API can be self-hosted (service and consuming application in the same solution) as discussed in this example or it can be deployed on IIS server. JSON is the widely used request type in services as it is supported by a wide range of client devices. Enjoy creating your own service.



ASP.NET MVC Hosting - HostForLIFEASP.NET :: Layouts And _Viewstart.cshtml In MVC

clock August 2, 2022 09:52 by author Peter

In this blog, we will discuss about Layouts and what is the significance of _viewstart.cshtml in Razor views. The intention of this blog is to understand the way how _viewstart.cshtml works in MVC. The reason to write this blog is I faced an issue with _viewstart.cshtml,  when I was using HandleError attribute.


What is Layout?
We all know that layouts are like the master pages in Webforms. Simply, the common UI code, which can be used in many views can go into a common view called layout. Usually, we place all the layout pages in the shared folder.

How to use Layouts in MVC?
The following are the different ways to use the layouts:

Using Layout in the View.
    @{  
    ViewBag.Title = "Index";  
    Layout = "~/Views/Shared/_Layout.cshtml";  
    }  

If we declare the code above, given above in the Index.cshtml, this will be rendered along with the HTML content of the _Layout.cshtml. This is the way, we regularly follow.

Assigning Layout in Controller's Action method.

If we work with real the time Applications, we will come across the situations, like to use the different layouts , based on the action called.

For example, I am looking for the list of the students. At this point, Layout would be different for admin and a Teacher but, both of them use same Razor View. Here, we will assign the Layout at an Action level.

We can see assigning the Layout at Action Method in the following code snippet.
If logged in as an admin:
    public List < Student > GetStudentList() {  
        return View("StudentList", "~/Views/Shared/AdminLayout.cshtml");  
    }  
    If Logged in as Teacher: public List < Student > GetStudentList() {  
        return View("StudentList", "~/Views/Shared/TeacherLayout.cshtml");  
    } 

Declaring Layout at _Viewstart.cshtml.

_Viewstate.cshtml plays an important and a tricky role in Razor views. It was introduced in MVC 3 along with Razor views. _Viewstart.cshtml is used to place common UI logic across the Views in the folder, where it is located. This means, the views in a single folder which is having _Viewstart.cshtml will be rendered along with it.

For example: If we observe the views folder of an MVC project, we will see _Viewstart.cshtml in the folder.

Thus, the views in Home and OpenAccess will be rendered along with the UI in _Viewstart.cshtml. We need not to declare anything in the views. This will be done automatically by the framework.

Benefit
By doing so, we can change the layout at a single place only. Otherwise, we have to change the number of views.

Notes
    The inner layouts like a layout in Home/Index will be overriden by _Viewstart.cshtml.
    We can have n-number of _Viewstart.cshtml files in a project. But each should be placed in a folder. Alll the views in the folder will be effected with this.
    _Viewstart.cshtml will be called after the inner view.(Ex: Home/Index)

Finally My problem was
I used HandlerError attribute in a controller. If any exception is caught in the Action method, it should go to error.cshtml, but It was not called as error.cshtml view, placed in a folder, which has _Viewstart.cshtml. Thus, _Viewstart.cshtml will be called after the error.cshtml. _Viewstart.cshtml has the layout,  where I had a Null Reference exception. At last, I removed Layout from _Viewstart and able to see error.cshtml page.

Conclustion
In this blog, we have discussed about the different ways to place layouts in MVC and use of _Viewstart.cshtml. Finally, use _Viewstart.cshtml effectively.



About HostForLIFE

HostForLIFE is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2019 Hosting, ASP.NET 5 Hosting, ASP.NET MVC 6 Hosting and SQL 2019 Hosting.


Month List

Tag cloud

Sign in