How to create custom 404 error handler in ASP.NET MVC

Custom 404 error handler – 404 Error refer to a not found resource/URL . Here’s how a default 404 Error notification looks in ASP.NET MVC.

custom 404 error handler

ASP.NET MVC has his own custom error handler that can be enable inside Web.Config file from your solution explorer.

Let’s Start:

First, to enable error redirection modify your Web.Config file.Search for <system.web> in your Web.Config and Add the code below inside the <system.web></system.web>.

Second, navigate to your Controller folder and create a controller ErrorController.This will serve as our custom error handler. Inside this controller create an action result method, let’s named it as NotFound this will return our custom view for 404 error.

Third, create a view for NotFound action result method.By default view for controller can be manually created inside View->Error folder.  Or by simply right clicking on your Not Found method inside ErrorController and selecting Add View.

custom 404 error handler

Custom Error Preview:

custom 404 error handler

 

Note: I used Bundle Config inside App_Start folder to call my custom style.css file.

custom 404 error handler

To add bundle you can simply copy the code below into your BundleConfig file where ~/Content/style.css is the location of your stylesheet and ~/Content/Custom/Error  is the name of your bundle.

  • Add(new StyleBundle(“~/Content/Custom/Error”).Include(

“~/Content/style.css”));

To call this bundle you can simply use @Styles.Render(“~/Content/Custom/Error”)

Code:

To add designed to the view we can also add icons. In my case i used the image below. Which i included inside image folder.  And used <img src=”~/images/smile.png” /> to include image in my view.

custom 404 error handler

Fourth, Create styles for your view. In my case I create a file name style.css inside content folder from solution explorer.

custom 404 error handler

Style.css Code:

And we are done. Every time a URL is invalid this error notification will appear instead of the default 404 error notification.

custom 404 error handler

Thank you for reading!! Happy coding!!

 

 

How to use WebClient in C# (System.Net.WebClient)

System.Net.WebClient
Using System.Net.WebClient class in consuming Web API.

System.Net.WebClient – The easiest way to download and upload data from and to a Web API is using Web Client. Here’s a few codes  to implement Web Client in 4 different method.

  • using System.Net;

Method: GET

Method: POST

Method: DELETE

Method: PUT


 

AngularJS CRUD Operation using ASP.NET MVC

I am a .NET Developer and I’m new in AngularJS. I started using AngularJS in about a week ago and I decided to create a full AngularJS CRUD Operation using ASP.NET MVC. This article will show you how I created a project with CRUD functionality using AngularJS.

For an overview of AngularJS, you can visit  AngularJS introduction from this site  https://docs.angularjs.org/guide/introduction.

AgularJS

To start, below are the summary of the steps I have done to fully implement AngularJS CRUD project.

AngularJS CRUD Operation using ASP.NET
  • Create SQL Database
  • Create CRUD Stored Procedure
  • Start a New ASP.NET MVC project
  • Create a separate Class for CRUD functions
  • Create CRUD Action Result in main controller( HomeController)
  • Design a View (Front End Design) with AngularJS App

To make this article much easier I copied all the code I have used in every associated class file in the steps above.

Let’s Start:

1. Create SQL Database:

To execute CRUD operation we need to have data storage. I assume you have already used SQL Database. Create a database and a table. In my case, I created a database named EmployeeDB and a table named EmployeeRecord. Image below.

AngularJS CRUD Operation using ASP.NET

2. Create CRUD Stored Procedure

If this is your first time using a SQL stored procedure you can refer to my previous article How to create a stored procedure.  Below are the Stored Procedures and the associated code I used.

AngularJS CRUD Operation using ASP.NET

 

Code:
DeleteEmployee Procedure

SQL Stored Procedure – InsertEmployee

SelectEmployee Procedure

UpdateEmployee Procedure

3. Start a New ASP.NET MVC project

Now, that we have already prepared our backend, which is the SQL Database and stored procedures. We can now start creating our project. Open your Visual Studio and create a new ASP.NET Web Application using MVC template. If you have no idea how to start a project you can visit my previous article on how to start in ASP.NET MVC.

4. Create a separate Class for CRUD functions

To organize our code I suggest we create a separate class containing all the connection we need to established connectivity to our SQL Stored Procedures.

But first, let’s create a folder inside our solution explorer by simply right-clicking on the project name and selecting Add > New Folder. See image below

AngularJS CRUD Operation using ASP.NET

Inside that folder create a Class. Add  Class by simply right-clicking your project name and select Add > Class. Below are the folder and class I created.

AngularJS CRUD Operation using ASP.NET

As you can see from the image above I named my folder as CRUD_function and my class as CRUD. Now, let’s start adding code. Open CRUD.cs and copy the code snippet below. This is where we put all our connection to the SQL Stored procedures.

Note:  To view your connection string you can refer to my previous article Manual viewing SQL Connection String.

CRUD.cs – Code:

5. Create CRUD Action Result in main controller( HomeController)

In this step, we will create an Action Result method in our main controller. If you are using the default MVC template, your default controller is HomeController. Located inside the folder Controller. Open HomeController. Copy the code snippet below.

HomeController.cs – Codes:

6. Design a View (Front End Design) with AngularJS App

After we have fully created all the necessary CRUD functions that we need, let’s start creating our front-end design with AngularJS framework. Navigate to your default view which is located inside the folder Views > Home > index.cshtml .Open index.cshtml and replace the code with the snippet below.

Project Preview:

AngularJS CRUD Operation using ASP.NET

Add of employee preview

AngularJS CRUD Operation using ASP.NET

Index.cshtml – Code: 

Note: with AngularJS Script

And we are done. Run your project and see if it works. You can comment below for technical questions about this article.

Thank you for reading!!

Happy Coding!!

Creating ASP.NET Web Service

ASP.NET Web Service – Web service is a software that is used to exchange XML-based information that uses the internet to interact with any other application called its client. This software provides a modular method that could be used by multiple applications through the web.

For detailed information about Web Service visit this thread on WIKIPEDIA

See tutorial below on starting your web service application in ASP.NET.

Let’s start:

Note:

  • I’m using Visual Studio 2013
  • Net Framework 3.5

Step 1. First start by opening your visual studio and create new Web Site project.

ASP.NET Web Service

Create New Project

Step 2. From new web site window choose .Net Framework 3.5 from the drop down just above your middle pane. See image below.

ASP.NET Web Service

.Net Framework 3.5

Step 3. Choose ASP.NET Web Service from the middle pane and rename your project

ASP.NET Web Service

ASP.NET Web Service

Step 4. The image below is the solution explorer of a newly created website project.

ASP.NET Web Service

Solution Explorer

Step 5. Open Service.cs. This file is your main class that contains your web method that is used for your web service method.

Note:

  • [WebMethod] >> this is used as a declaration for the method that should be accessible on the web.
  • This example code returns Hello World string as the output.

This image is the default code generated for a new Web Site project.

ASP.NET Web Service

Service.cs

Step 6. To run project hit F5 on your keyboard to run project in debugging mode or hit CTRL + f5 to run without debugging mode. Your project will display on a browser containing your method HelloWorld().

 

ASP.NET Web Service

Web Service

Step 7. To test how web service work click on your method and click  invoke button.

ASP.NET Web Service

Invoke

It should bring you to a new tab containing your return value Hello World. It should look like the image shown below.

ASP.NET Web Service

HelloWorld return value

You have just created your first ASP.NET Web Service project.

You can start adding your method now and consume it in a client side application.

Thank you for reading. Happy coding!!

 


Post you may like:

[pt_view id=”2384ae03it”]

 

Restful Web Services Tutorial with ASP.NET MVC

Restful Web Services Tutorial

Restful Web Services Tutorial – From my previous Article on how to Create Web API in ASP.NET. We have created an API method that will return Hello + the name input by the user. Now in this article let’s consume that API using a client Application.

Let’s start: – Restful Web Services Tutorial

1. Create a new ASP.NET MVC Web Application Project.

Create New Project

2. I assume you have already created a project. Now we will use again the default Controller of MVC which is HomeController. Open HomeController by navigating to Solution explorer->Controller folder and open HomeController.

HomeController

3. From your Index function inside your HomeController, lets create additional code that will connect as to the API we created from the previous blogs ASP.NET WEB API using ASP.NET MVC.

Add below Code to your index.

  • using System.Net » For Webclient(). Which is use to connect to our Web API
  • using System.Data » For DataTable()
  • using Newtonsoft.Json » JSON
  • Viewbag.Name = response » dynamically share values from our controller to our view.
  • John » Parameter value. It could be anything you want to supply.

 

Code:

The image below is the screenshot of my HomeController code.

Home Controller Code

4. Now to display this in our view and to make it as simple as possible I use ViewBag Property to pass data to our view. Now navigate to your View (index.cshtml) under Views->Home folder and open index.cshtml.

Index.cshtml

5. Replace the code from your actual index.cshtml using the code shown in the image below. This display whatever we save to our ViewBag.Name Property.

Index.cshtml

6. Lastly, Run your project using f5 to run your project in debugging mode or CTRL + f5 to run project without debugging mode. This should output parameter name we declare in this code from our index() method in HomeController.

  • string url = “http://localhost:41480/Home/HelloWorld?name=” + “John”;

If we replace the name parameter John into Regie from the code above the output should now be Hello Regie. But because I use John in my code the image below shows Hello John output.

 

Note:  Because we are using local project you need to run both API and client application to access both project. You can also publish your API in your local IIS read this thread How to Host ASP.NET Web App in IIS.

 

Output

That’s all we need in consuming Web API in ASP.NET.

Comments are greatly appreciated to improve my blog writing technique.

Thank you for reading. Happy Coding!

You might to want to revisit this blog  Create Web API in ASP.NET.


Post you may like:

[pt_view id=”2384ae03it”]

Rest API Application – ASP.NET MVC

Rest API Application – ASP.NET WEB API is a framework that allows you to build an HTTP service. This service can be accessed online using HTTP requests. API’s can include all possible method that exposed data from a database. Like INSERT, SELECT, DELETE and UPDATE. And because API is an HTTP service its method is accessible using a URL.

Let’s take a look at a simple example below on the actual way on how the API is created and behave in .NET framework.

Let’s Start: – Rest API Application

Step 1. Open your visual studio and go to File->New->Project. A New  Project dialog window will open.

Rest API Application

Create new Project

Step 2. From the left pane of New Project window select Templates->Visual C# -> Web. Then from the middle pane select ASP.NET Web Application. And name your application, in my case I name it as SampleAPI. Click “OK” if you’re done.

Rest API Application

New Project

Rest API Application

Step 3. Select a template. To make it simple we will use Web API with default MVC template. Choose Web API template and check MVC and Web API from checkbox right below you’re template option. See the image below.

Rest API Application

Templates

Because we are using MVC template for this project your start page will look like a standard ASP.NET MVC Web Application. But we are not really after the view in this project. Method inside API’s is access directly using a URL. See image below.

Rest API Application

Start View

The image below is the default Folder structure created in MVC Framework.

Rest API Application

Folder Structure

 

Step 4. Now, after you have created a Web API project navigate to your solution explorer and open HomeController inside Controller folder. As I discussed from my previous blogs about MVC, HomeController is the default controller of MVC template in ASP.NET Web Application.

Rest API Application

HomeController

Step 5. For simplicity and better understanding of this article we will create a simple method that will return name input by a user.

Ex. John => Hello John 

I name the method HelloWorld() but instead of returning Hello world we will return Hello + the name input by the user. See image below for the code.

Rest API Application

Hello World

Step 6. To access the method we just created run your project using f5 command for debugging mode.  And use the URL shown in the image below to access the method.

  • URL format localhost:port#/ControllerName/MethodName?Parameter=value.
  • Value => Supplied in the client side application

If the user input Regie as the name parameter the output would be Hello Regie

  • localhost:41480/Home/HelloWorld?name=Regie

 

Rest API Application

Output

Rest API Application

This might be a simple example but this will help you start your own WEB API Project. You can create additional method like connecting to your database and return a set of list or Update data from your database. This is all possible if you just know the concept of API’s.

To consume this API using ASP.NET MVC visit this thread Consume Web API using ASP.NET MVC

Thank you for reading. Happy Coding!!


Post you may like:

[pt_view id=”2384ae03it”]

ASP.NET MVC Entity Framework:Code First Approach

Populate HTML Table using JQUERY

ASP.NET MVC Entity framework code first approach allows you to create classes and use entity framework to generate your Table base on your design class. It has similarity with the model first approach, however it does not generate edmx file. To determine their differences visit this blog  Entity Framework Model first approach for the actual process on how the database is generated in this approach. To proceed with Code first approach below is the tutorial on how the database is generated in Code first approach.

Let’s start:

      Note:

1. I assume you have already created your project. Let’s proceed by adding class to our project. This will serve as our model so I prefer to put it inside Models folder. To add new item right click Models folder, choose Add then select Class. See image below for your guide.

Entity Framework

Add new item

2. From Add new item window, name your class. In my case I name it as Employee_Listing.

Entity Framework

Name your class

3. Copy the code below. This will serve as our model to be use by entity framework in generating our table design.

Code:

4. Now add another class for the DBContext of entity framework. This binds our model to Entity Framework and generate database schema for our model class.

Entity Framework

Employee_ListingDBContext

5.Open the file we just created and copy the code below.

Code:

6. The image below is the classes I created inside my Models folder.

Entity Framework

Model Folder

7. In order for us to connect to the desired database where we want to create our table. We need to add connection string to our web config file. Open your web.config and find this line <connectionStrings></connectionString>. Inside this line insert your Database connection string.

Note:

  • Employee_ListingDBContext –> DBCOntext class we created earlier. This should be name as the class where you bind your model into Entity Framework.
  • (localdb)\Projects-> This is my local SQL Server .
  • providerName=”System.Data.SqlClient” –> specify your provider name.

 

Code:

8. In order for me to execute the classes I made earlier I inserted a dummy data to the table and create a Table design in my Views. Open your HomeController.cs this is the default controller used to load the default view of your Web Application. See image below to locate file from your solution explorer.

Entity Framework

Solution Explorer

9. Below are the codes I used in my HomeController. From my index function I call my Entity framework class which is Employee_ListingDBContext and added dummy data to my model to be inserted to my table. I also created a list variable with our table model design where I store the data I selected from our database table and pass it to my views where I populate the data to my HTML Table.

Code:

10. Open your Index.cshtml file and copy the code below.To locate your index.cshtml navigate to Views->Home->index.cshtml or by simply right clicking anywhere inside your index function inside your HomeController and selecting Go To View option.

Entity Framework

Go To View

From your view, copy and paste codes below. This will create a table and populate data from our controller.

Note:

  • @model IEnumerable<CodeFirst_Approach.Models.Employee_Listing> – Give as access to the model list we pass from our controller.
  • @ -> drop to C# code.

Code:

11. Lastly, run your application by pressing F5 to run project in debugging mode or CTRL + F5 to run project without debugging mode.

 

Project final output:

Entity Framework

Final output

 

 


Post you may like:

 

[pt_view id=”2384ae03it”]

How: Adding Entity Framework Reference using NuGet

Adding Entity Framework

If you have already added Entity Framework you might want to check this thread ASP.NET MVC using EF for actual using of Entity framework in your code. If this is your first time you can continue reading steps below on Adding Entity Framework.

Let’s Start: – Adding Entity Framework Reference

1. Open NuGet Package Manager to add EntityFramework. Go to Tools->NuGet Package Manager ->Manage NuGet Packages for Solution. 

Adding Entity Framework

2. Search for EntityFramework and click install button.

Adding Entity Framework

Search For EntityFramework

3. Wait for NuGet Package Manager to install EntityFramework.

Adding Entity Framework

4. The image below is the view of Entity Framework after it is already installed.

Adding Entity Framework

5. To check if EntityFramework is successfully added to your project go to your solution explorer and under your reference EntityFramework should be found.

Adding Entity Framework

Project Reference

Entity Framework

You have successfully added Entity Framework to your project. You can now use it in your ASP.NET MVC Web Application.

 


You might want to check this thread..

 

[pt_view id=”d88f6acsu0″]

ASP.NET Entity Framework: Model First Approach (MVC)

Model first Approach is ASP.NET Entity framework functionality which creates a new model using entity framework designer and generate database schema from the model design. This is all found in EDMX(.edmx extension) file.

To fully understand how this entity framework approach work. I have created a simple tutorial on how to execute Model First Approach.

     Note:

Let’s start:
1. First add Add New Item to your project. In my case because it is an MVC Application I prefer placing it inside my Models folder. To add, right click on Models folder and click Add and choose New Item.

Entity Framework

Add New Item

2. Add ADO.NET Entity Data Model. Under Visual C# select Data and in the middle pane select ADO.NET Entity Data Model.

Entity Framework

ADO.NET Entity Data Model

3. Choose Empty Model then click “Finish” .

Entity Framework

Empty Model

4. After you have added ADO.NET Entity Data Model it will automatically create EDMX(.edmx extension) file. Like the image shown below.

Entity Framework

Designer

5. Add entity for your model. Right click anywhere inside EDMX designer click Add New->Entity. Refer to the image below.

Entity Framework

Add New Entity

6. Name your entity. In my case I name it as Employee and Entity Set is automatically generated by the framework as Employees.

Entity Framework

Name Entity

7. Add Scalar Property which represent your table column. To Add, right click anywhere inside your Entity and Select Add New – > Scalar Property.

Entity Framework

Add Scalar property

8. The image below is the overview of the designer with the toolbox that contains tools you can use to design your entity.

Entity Framework

Designer

9. Generate Database from Model. This will generate .sql file inside your EDMX file which contains command used to generate your database. Right click anywhere inside your designer and select Generate Database from Model.

Entity Framework

Generate Database from Model

10. From Generate Database Wizard window click “Next” to proceed.

Entity Framework

Generate Database Wizard

11. Entity Framework generate Data Definition Language(DDL) that contains command in generating Database from your model design. Click “Finish”.

Entity Framework

Data Definition Language

12. It will create .sql file that contains needed command to create your Database Schema.

Entity Framework

Employee.edmx.sql

13. Below are the codes inside Employee.edmx.sql file.

Note:
• USE[master]-> Database name. This is where I created my table when I hit on execute command with my file.

Code:

14. Open Employee.edmx.sql file and execute command to create database. Right click anywhere inside your Employee.edmx.sql editor and select Execute. See image below.

Entity Framework

Execute Command

15. A dialog box will pop-up asking for your server name where you want to create your table.

Entity Framework

Connect to server

16. Message will appear of saying “Command(s) completed successfully” .

Entity Framework

17. The image below is the table created by Entity Framework.

Entity Framework

Employees Table

You have successfully created your table. By this time you can now use Entity Framework Model first approach in your ASP.Net MVC Web application.
Thank you for reading. !!

 


Post you may like:

[pt_view id=”2384ae03it”]

1 2