All posts by Thiyagu

Dynamically Adding meta tags in asp.net mvc

In this blog post, I am going to explain how we can create a meta tag dynamically using Asp .Net MVC. We are aware that Meta tag plays very important roles in Search engine optimization. It is necessary to add meta tag for best ranking on search engines. Let we discuss with simple example.

Controller :

From the below code, BindMetaTag method which will return a string with meta tags. This method will create a meta tag string and it will return to the calling method. Here I am using view bag to store the dynamically created meta tag string for binding in the view.

public ActionResult Index()
{
ViewBag.LoadMetaTag = BindMetaTag();
return View();
}

public string BindMetaTag()
{
System.Text.StringBuilder strDynamicMetaTag = new System.Text.StringBuilder();
strDynamicMetaTag.AppendFormat(@"<meta content='{0}' name='Keywords'/>", "Dotnet-helpers");
strDynamicMetaTag.AppendFormat(@"<meta content='{0}' name='Descption'/>", "creating meta tags dynamically in"+ " asp.net mvc by dotnet-helpers.com");
return strDynamicMetaTag.ToString();
}

View :

Here in the below code, @Html.Raw method is used to embed meta tag in _layout.cshtml page. This HTML.Raw method will embed output to head tag section without encoding html.

@Html.Raw(ViewBag.LoadMetaTag)

<h2>Dynamically creating meta tags in asp.net mvc</h2>

OutPut :

Now once you run your application and click on view source you will find meta tag for home page as show below.

dotnet-helpers-adding meta tag using mvc -thiyagu

 

Keep Cool Coding….

Understanding Attribute Routing in MVC 5

In this post we are going to discuss about the new feature of routing in ASP.NET MVC5 known as Attribute Routing. Attributes Routing are used to define the routes in controller/action directly. The main purpose of attribute routing is to control the URLs by define directly on action and the controller in the application.

When to use?

In some scenario, convention-based routing is complex to support certain URL patterns. This can achieve easily by using Attribute Routing.

For example, if user have ordering books based on authors, items based on color and so on. Then URL will look like /user/1/orders, this type of URL is difficult to match using the convention-based routing. But it can be achieve by convention-based routing but it will take our extra effort for this. By using attribute routing, it can be done much easier, by defining on the controller/action.

Defining Attribute Routing in ASP.NET MVC

Attribute routing can be define in two ways

  • Controller level Attribute Routing
  • Action level Attribute Routing

Register Attribute Routing

Attribute Routing use RoutePrefix and Route attributes to achieve the routing. The RoutePrefix attribute is used on the controller to specify a route prefix for all actions inside the specific controller. The Route attribute used on action method to allows us to specify the route on the action method. Before that we need to register attribute routing in the RouteConfig.cs using routes.MapMvcAttributeRoutes().

public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute(“{resource}.axd/{*pathInfo}”);
//Register Attribute Based Routing
routes.MapMvcAttributeRoutes();
//convention-based routing
routes.MapRoute(
name: “Default”,
url: “{controller}/{action}/{id}”,
defaults: new { controller = “Home”, action = “Index”, id = UrlParameter.Optional }
);
}

Controller level Attribute Routing : [RoutePrefix()]

Controller level attribute will apply to all actions which is present within the controller unless a specific attribute route is added to an action.

[RoutePrefix(“dotnet-helpers”)]
[Route(“{action=index}”)] //default action
public class HomeController : Controller
{
//route: /dotnet-helpers/Index
public ActionResult Index()
{
return View();
}
}

OUTPUT :

Action level Attribute Routing : [Route()]

Action level Attribute routing will be for specific action with in the controller.

[RoutePrefix(“dotnet-helpers”)]
[Route(“{action=index}”)]
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[Route(“About”)] 
public ActionResult Contact()
{
ViewBag.Message = “Your contact page.”;
return View();
}
}

OUTPUT :

How to use Attribute Route in Area : [RouteArea()]

RouteArea attribute is used to define attribute routing for a controller which is present within Area.

[RouteArea(“SuperAdmin”)]
[RoutePrefix(“dotnet-helpers”)]
[Route(“{action=index}”)]
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[Route(“About”)] //default action
public ActionResult Contact()
{
ViewBag.Message = “Your contact page.”;
return View();
}
}

Note :

  • routes.MapMvcAttributeRoutes() : It will map all the routes that is defined as attributes.
  • The main advantage of using Attribute routing is the flexibility  that give us the excellent control over URL.

Retrieve Views from Different Folders in MVC

In this post we will discuss how to use the view which is placed inside another folder in our application and
how to use that view in our controller. In simple, if we place the view inside the folder views -> Users -> Admin -> index.cshtml instead of views -> Users -> index.cshtml.

When to use?

In the below image, all the views has been placed under Views -> Users. Here we can see there is no structured hierarchy of the views. So we are creating a separate folder for Admin, Non-Admin, Super Admin to create a view based on their role.

Creating View in different folder :

EG :  views -> Users -> Admin -> index.cshtml)

For the default view location the action will be like below

public ActionResult Admin()
{
return View();
}
public ActionResult NonAdmin()
{
return View();
}
public ActionResult SuperAdmin()
{
return View();
}

For the customized view location, the action will be look below. We can’t redirect particular view from here.

public ActionResult Admin()
{
return View(“Admin/AdminHomePage”);
}
public ActionResult NonAdmin()
{
return View(“NonAdmin/NonAdminHomePage”);
}
public ActionResult SuperAdmin()
{
return View(“SuperAdmin/SuperAdminHomePage”);
}

Creating Controller based on the Customized View Location :

Here it can’t redirect to the particular view location by right click -> Go To View option. It will show “Unable to find a matching view.”

 

Keep Cool Coding !!!

Logging Errors using ELMAH In ASP.NET MVC- Part I

What is ELMAH?

ELMAH provide way for logging Error at runtime in a Local/Production environment.  ELMAH is a open source error logging library/dll that includes features like error filtering and able to  view the error logs by a web page (localhost:50287/elmah.axd). It would very difficult to track/debug the error after code has been moved to production environment. To avoid this type of difficulties we are using ELMAH for logging.

Note : The main purpose of ELMAH it to log all the unhandled exceptions in our application.

Implementing ELMAH in our Application :

STEP 1: Installing ELMAH

Install ELMAH using NuGet, go to Tools -> Library Package Manager -> Package Manager console and type “Install-Package elmah” as shown in below.

STEP 2:

After successfull installation, elmah will add required library in our application and update the web.config file. Verify whether below changes has been updated in the webconfig after the successfull installation.

<?xml version="1.0" encoding="utf-8"?>
<configuration>

<configSections>
<sectionGroup name="elmah">
<section name="security" requirePermission="false" type="Elmah.SecuritySectionHandler, Elmah" />
<section name="errorLog" requirePermission="false" type="Elmah.ErrorLogSectionHandler, Elmah" />
<section name="errorMail" requirePermission="false" type="Elmah.ErrorMailSectionHandler, Elmah" />
<section name="errorFilter" requirePermission="false" type="Elmah.ErrorFilterSectionHandler, Elmah" />
</sectionGroup>
</configSections>

<elmah>
//Make chage to YES, if we need to access it in remote
<security allowRemoteAccess="No" />
</elmah>

<system.web>
<httpModules>
<add name="ErrorLog" type="Elmah.ErrorLogModule, Elmah" />
<add name="ErrorMail" type="Elmah.ErrorMailModule, Elmah" />
<add name="ErrorFilter" type="Elmah.ErrorFilterModule, Elmah" />
</httpModules>
<httpHandlers>
<add verb="POST,GET,HEAD" path="elmah.axd" type="Elmah.ErrorLogPageFactory, Elmah" />
</httpHandlers>
</system.web>

<system.webServer>
<handlers>
<add name="ELMAH" verb="POST,GET,HEAD" path="elmah.axd" type="Elmah.ErrorLogPageFactory, Elmah" preCondition="integratedMode" />
</handlers>
</system.webServer>

</configuration>

STEP 3: 

Run the application and try to access contoller/action which is not present in our application for tracking the error.
After that include elmah.axd at the end of the url to show the errors which has been caught from starting as shown below.

NOTE : If you not able to access the elmah.axd page then include the below line in Global.asax

RouteTable.Routes.Ignore(“{resource}.axd/{*pathInfo}”);

We will discuss more about ELMAH in upcoming posts.

Keep cool coding…

 

Difference between ViewBag, ViewData, TempData in ASP.NET MVC

ASP.NET MVC provide ViewData, ViewBag and TempData for maintaining the data between controller to view, controller to action, action to action.

Similarities between ViewBag & ViewData :

  • ViewBag & ViewData are used to maintain data while travelling from controller to view.
  • This communication is only for server call, it becomes null if redirect occurs.
  • It’s life span is short because the data will became null when redirection occurs. The main pupose of viewData and ViewBag is to maintain the data while travelling from controller to view.

ViewData

  • ViewData is a dictionary object. It is derived from viewDataDictionary class.
  • Typecasting is required for complex data type and need to checks for null values to avoid error

ViewBag

  • ViewBag is a dynamic property (The properties that are associated with the dynamic are ignored at the compile time).
  • It doesn’t require typecasting.

TempData

  • TempData is derived from TempDataDictionary class
  • Tempdata helps to store/preserve values within in a single request. TempData preserve values for the next request based on 4 different conditions in MVC. More about temp data click here (It helps to maintain the data when we move from one controller to another controller or from one action to another action).
  • It requires typecasting for complex data type and checks for null values to avoid error.

 

Keep Cool Coding….

 

State Management in ASP.NET MVC – ViewData, ViewBag and TempData in MVC

In ASP .NET MVC, ViewData, View Bag, TempData is used to maintain the state in our page/view. Viewdata, ViewBag is used to transfer date/information from controller to view in the current request. TempData use to transfer data from controller to another controller. It has capable of maintaining the data to not only on current request, it can maintain the data in next HTTP requests.

Flow Diagram :

ViewData

ViewData is a dictionary object, which used to maintain data from controller to view. It is derived from viewDataDictionary class. It requires typecasting for complex data and need to check null values to avoid error as shown below.

Note: The data inside the viewdata will be available in the current request only so the value become NULL if redirection occurs.

Example:

Controller

public ActionResult Index()
{
var dotnetproduct = new dotnetproduct(name: “MVC”);
ViewData[“dotnet-product”] = dotnetproduct;

ViewData[“Name”] = “dotnet-helpers-ViewBag”;
return View();
}

View : 

@ViewData[“Name”]

@{
var ViewDataproduct = ViewData[“dotnetproduct”] as dotnet-product; <!– Need to Typecast –>
if (@ViewDataproduct != null) <!– Need to check for NULL value –>
{
// Your Logic
}
}

ViewBag

ViewBag is a dynamic property (The  properties that are associated with the dynamic are ignored at the compile time). And it has same purpose of viewdata for maintain the data from controller to view. It doesn’t require typecasting.

Note: The data inside the viewdata will be available in the current request only so the value become NULL if redirection occurs.

Example:

Controller

public ActionResult Index()
{
ViewBag.Name = “dotnet-helpers-ViewData”;
return View();
}

View :

@ViewData.Name

TempData

TempData is a dictionary derived from TempDataDictionary class. It differ from ViewBag and ViewData by it’s  life cycle of the object. TempData keeps the data up to next HTTP Request.

Note: The data inside the Tempdata will be available in the next request. In simple, it helps to maintain data when we move from one controller to other controller or from one action to other action. It requires typecasting for complex data type and check for null values to avoid error.

Controller

public ActionResult Index()
{
TempData[“Name”] = “dotnet-helpers-TempData”;
return RedirectToAction(“CheckTempData“);
}

public ActionResult CheckTempData()
{
var model= TempData[“Name”];
return View(Name);
}

View :

@ViewData[“Name”]

Output : dotnet-helpers-TempData

Where to Use?

  • ViewBag is a dynamic object, so we can add strongly typed objects, primitive values, etc that we need. We can choose ViewBag while passing dynamic data from view to controller.
  • ViewData is a ViewDataDictionary, it can be accessed through a key (string). We can choose ViewDate while passing data from view to controller.
  • ViewData need typecasting while getting the original object/data.
  • TempData is a dictionary derived from TempDataDictionary class. It can be used when we need to carry data from one controller to another controller or one action to another action. It also requires typecasting while getting the original object/data. The data had removed when view reads them. For  more detail about TempData click  here
  • ViewBag,ViewData can’t pass data back to controller.

Keep Cool Coding…

 

Handling Unknown Actions in ASP.NET MVC

Introduction:

In MVC, the request will be in the form of controller and action ( it is the name of controller and with action methods). So when browser request came, route will find the matched controller and action to response the browser with output. Here we are going to discuss about how to render view even when corresponding action does not exit. We will aware it will throw an error if matched action is not found inside the controller.

When to use MVCHandleUnknownAction ?

In below image, we can see each controller action has it’s own view in the application. One thing we can identify that Article1,Article2,Article3 has same piece of code. So here we having unnecessary redundant code in our application.

To over come this problem, in MVC we are using MVCHandleUnknownAction method to handle the absence of action method inside the controller.

With absence of Action in controller:

Example :

In above image,we can see each controller action has it’s own view in the application. If we remove the action from the controller then it will thrown an error while requesting the same action as like below image.

Handling Unknown Actions in ASP.NET MVC :

To render view even when corresponding action does not exit ( and alos to avoid redundant code), here we implementing the MVC HandleUnknownAction method instead of redundant Action (Article1,Article2,Article3)  in controller like Below Code.

public class HandleUnknownActionController : Controller
{
// GET: HandleUnknownAction
public ActionResult Index()
{
return View();
}
protected override void HandleUnknownAction(string actionName)
{
try
{
this.View(actionName).ExecuteResult(this.ControllerContext);
}
catch(Exception ex){// here we can catch the view not found error}
}
}

While browser request the articl1 action (eg: http://localhost:8080/HandleUnknownAction/article1), it  tried to access the article1 action inside the  controller. But there is no presence of Article1 action, so it has been caught by HandleUnKnownAction method as show below.

From the above code, HandleUnKnownAction method catch the incoming request and redirect the particular view if it present in the application. If its unable to find the view in-side our solution then it will be handle by the catch block.

OUTPUT :

 

Keep Cool Coding…….

Difference between Model/Domain Model and ViewModel in MVC

In this post, we are going to discuss about the difference between Model and ViewModel with MVC. Before that we are going to start with what is meant by model and What is the Difference between Model and ViewModel in MVC.

What is Model/Domain Model:

Domain Model represents a domain object in our application like a Entity Framwork ,SQL…(while using ORM).

The model is an object, using that we can pass the information/data to the database. The main purpose of the model is to perform operations on that and render on the view/save to the database. The modelhelps us in creating, editing, updating, deleting operation in our application.

Example:

Let we consider EmployeeDetails which was created using Entity Framework.

public class EmployeeDetails
{
public int EmployeeId { get; set; }
public string FirstName { get; set; }
public string LastName{ get; set; }
public string Address { get; set; }
public int Age { get; set; }
public Department EmpDepartment { get; set; }
}

From above model, we understood domain model has created based on DB/table structure.

What is ViewModel:

MVC ViewModel is similar to ‘model’. But the major difference between ‘Model’ and ‘ViewModel’
is that view model is only used to rendering(ie., displaying information) information in views.

Why we moving to View Model?

In most of the times, our UI/page Presentation requirements are different from domain requirements. Based on the requirement, we add/remove the attribute to the domain model. Let consider, in our view we need to display only EmployeedId, FirstName, EmpDepartment. So we are going to remove the unwanted details in our model, based on the UI requirement as shown below.

public class EmployeeDetails
{
public int EmployeeId { get; set; }
public string FirstName { get; set; }
public Department EmpDepartment { get; set; }
}

Note :

  • ViewModels gives us more flexibility to organize based on our requirements.
  • ViewModels help us to manage data in our applications when we need to work with complex data.
  • It gives more flexibility for managing more than one data source.

Understanding Routing in ASP.NET MVC – PART II

We have already discussed basic about ASP.NET MVC routing here. So in this post we are going to discuss about more on routing with examples.

What is Routing?

Routing is set of rules/pattern matching system that monitor the incoming request from the broswer and set matched location to process further.

The Routing engine uses the virtual route table which helps to find the matching pattern for the incoming request (URL) from the browser.

The route has the following 3 segments:

Controller : define the controller{controller}
Action : define the action{action}
Parameter : define the parameter{id}

Let me explain the above segments with examples.

Example 1: With No paramerter

We can find Route configuration inside App_Start (Folder) –> RouteConfig.cs

Controller:

public ActionResult Index()
{
return View();
}

RouteConfig.cs:

public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute(“{resource}.axd/{*pathInfo}”);
routes.MapRoute(
name: “Default”,
url: “api/{controller}/{action}/{id}”,
defaults: new { id = UrlParameter.Optional });
}
}

We can also state that the default or optional values are provided for all the three segments. The Controller has a default value of “Home”, the action has a default value of “Index” and id is an optional value.

Let us assume www.dotnet-helpers/Home/Index/ has been requested from the browser. Then the default route maps this URL shown below.

controller : Home
action : Index

Example 2: With Parameter

Controller:

public ActionResult Index()
{
return View();
}
public ActionResult Index1(int id)
{
return View();
}

The default route will handle the below requests and redirect to the matched controller and action method ( ie.,  index () and index1 (int id)).

http://localhost:50287/dotnet_helpers/index
http://localhost:50287/dotnet_helpers/index1/1

Let us assume www.dotnet-helpers/Home/Index/500 has been requested from the browser. Then the default route maps URL shown below.

controller : Home
action : Index
id : 3

 

Understanding Routing in ASP.NET MVC – PART 1

Introduction

In this article we are going to discuss about the basic ASP.NET MVC Routing, how it works and difference between ASP.NET web Form request and ASP.NET MVC request.

What is Routing?

Routing is set of rules/pattern matching system that monitors the incoming request from the browser and set matched location to process further.

The Routing engine uses the virtual route table which helps to finding the matching pattern for the incoming request (URL) from the browser.

Request handle in webform and ASP.NET MVC :

In ASP.NET Web forms, the request from the browser is mapped to the page which is physically present in our application/website directory like Home.aspx, AboutUs.aspx.

But in ASP.NET MVC, the request needs to be mapped to a controller and action. In ASP.NET MVC, we don’t have concept of physical file(like aspx).

Difference between In ASP.NET Web Form and  ASP.NET MVC request?

In MVC, we are having the controller and action methods. Each controller has multiple action methods.
Routing takes care of the mapping strategy for mapping request URLs to the controllers and action methods. we know already that .aspx will be available in the ASP.NET Web form request as shown below. But in MVC we dont have any extension like this because it won’t have physical file location (one controller have multiple action).

ASP.NET Web forms request : https://dotnet-helpers.com/MVCRoute/Route.aspx

ASP.NET MVC request : https://dotnet-helpers.com/MVCRoute/Route

MVCRoute is a Controller
Route  is an Action

From above, .aspx is physical file which is present in the application directory so no separate mechanism for handling the request. In ASP.NET MVC, there is no physical file for route, it contains controller and the action.

Flow of Routing :

From above flow, the request is handled by routing. First route engine parses the  incoming URL and  match the request with virtual route table. If request match with the pattern present in the route table then it will redirect to the particular controller and action. If match not found in the route pattern then it will show the 404 error.

Here we have discussed the basics of the routing concept. In upcoming article we will discuss more in depth about routing. Happy coding.