Category Archives: MVC

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 :

statemanagement in MVC -dotnet-helpers

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.

How to Persist Data with TempData using Peek and Keep in MVC

In this post we are going to discuss about how to preserve the value in next request using TempData Peek and Keep in ASP.NET MVC.

What is TempData?

Tempdata helps to store/preserve values within in a single request. This is the one of the concept for maintaining state in ASP .Net MVC.

How to store/persist data in next request?

TempData preserve values for the next request in 4 different conditions in MVC. They are

  • Condition 1 – Not Read in First Request.
  • Condition 2 – Read In First Request.
  • Condition 3 – Read & persist using Keep.
  • Condition 4 – Persist using Peek and Read.

Let us discuss this one by one in detail.

Not Read in First Request : If we do not read “TempData” in the current request then “TempData” value will be persisted for the next request.
Read In First Request : If we read “TempData” in the current request then “TempData” value will be not persist for the next request.
Read & Persist using Keep : If we read “TempData” in the current request and we can keep method to persist TempData for the next request. In MVC, we are having void keep() and  void keep(string key) methods to persist the data.

Example :

var readInfo = TempData

[“dotnet-helpers-info”];
TempData.Keep(“dotnet-helpers-info”);
OR
var readInfo = TempData[“dotnet-helpers-info”];
TempData.Keep();

Persist using Peek and Read : If we read “TempData” using the Peek method then then the data will persist in the next request.

Example :

var readInfo = TempData.Peek(“dotnet-helpers-info”);

Flow Chart

Server-Side Comment in MVC

In this post we are going to discuss about new feature in mvc, that is server-side comment.

What is Client side comments?

(<!– –>) it is a Comment which is support by HTML. It main purpose to prevent a browser from running or displaying the code/content in the application.

What is Server Side Comments?

In ASP.NET MVC supports a server-side comment which make code/content completely disable in the page.

ASP.NET Web Forms supports a server-side comment that you can use to completely disable content/code within a page. Using this compiler completely ignore everything within the @*– –*@ blocks at parse time, and removes the content completely when assembling the page in the browser(in simple it won’t show the content/code in the browser). So the contents wasn’t there at the page while loading in browser.

Syntax for Server side comment :

MVC Razor : @*– –*@
ASP WebForm : <%– –%>

Why Server Side Comments is needed?

The problem with using Client side comments approach, is that the content contained within the comment in our application is still sent to the client from the server unnecessarily.Then the server-side code within the comment will still execute. This will create extra load to the server. To overcome this scenario we moved to the server side comments

Example: Client Side Comment

Include <!–<h1>Bundling in dotnet-helpers.com</h1>–> in view/form, then the output will be

Example: Server Side Comment

Include @*<h1>Bundling in dotnet-helpers.com</h1>*@ in view/form, then the output will be

Note :

  •  In Client Side Comment, the commented code/content will be loading to the browser side as shown in example above
  •  In Server Side Comment, the commented code/content will not be load to the browser side as shown in example above

Layouts, RenderBody, RenderSection and RenderPage in ASP.NET MVC

What is Layout?

The main focus of the developers will be to maintain a consistent look and fell across the application (ie., all the pages within our website/application). To achieve this, Razor View Engine support a concept with a feature called “layouts”. Which can allow us to define a common template, and then we can able to inherit its look and feel across all the views/pages on our Application to make consistent look and feel.

MVC layout is same like as masterpage concept in webforms.

1. RenderBody:

What is it?

As per below example, the layout view contains html Doctype, head and body elements as like other view/page. The main difference is call to RenderBody() and RenderSection() methods in the layout.

RenderBody acts like a placeholder for other views. For example, Index.cshtml is a view which rendered layout view,where the RenderBody() method is being called.

Syntax : @RenderBody()

Example :

_Layout.cshtml

<!DOCTYPE html>
<html>
<head><title></title></head>
<body><div class=”body-content”>@RenderBody()<footer> …</footer></div>
</body>
</html>

Index.cshtml

//We can render layout in our view by calling “Layout=~/Views/Shared/_Layout.cshtml”

@{ Layout=~/Views/Shared/_Layout.cshtml}

//The below content will be render inside the @RenderBody section in layout

<div><h5>This content will be placed in the @RenderBody() section</h5></div>

2. RenderSection

What is it?

The layout have only contain one RenderBody method, but can have multiple sections. RenderSection method is used to create sections in layout. RenderSection runs code blocks which we define in our content pages.

Syntax : @RenderSection(“section name”, Boolean value)

Explanation :

In ASP.NET MVC by default, sections are mandatory. To handle this/make this optional, just we need to utilize the second parameter “false”.

@RenderSection(“scripts”, false) – Make the Scripts-RenderSection non-mandatory in all the pages/views which included  _Layout.cshtml

@RenderSection(“scripts”, true) – Make the Scripts-RenderSection mandatory in all the pages/views which included  _Layout.cshtml

Example :

_Layout.cshtml

<!DOCTYPE html>
<html>
<head><title>….</title></head><body><div class=”body-content”>
@RenderBody()
@RenderSection(“scripts”, required: false)
</div>
</body>
</html>

Index.cshtml

@{ Layout=~/Views/Shared/_Layout.cshtml}

@section scripts {<script type=”text/javascript”>alert(‘Dotnet-helpers’);</script>}

3. RenderPage

What is it?

RenderPage method is used to render other exists view in our application.In simple, the method allows us to render
code from an other view.
A layout page can have multiple RenderPage method.

Syntax: @RenderPage(“~/Views/Shared/_LoginPartial.cshtml”,model)

Explanation :

This method takes either one or two parameters.The first parameter refer the physical location of the file and second is an optional array of objects/model that can be passed into the view.

Where to Use?

If we want to keep the footer and header in separate view. In this scenario, we need to call two separate view in to the layout using RenderPage method.

Example:

Create two view partial views under the shared folder to make it as shared.

view 1 : _Header.cshtml
view 2 : _Footer.cshtml

_Layout.cshtml :

<!DOCTYPE html>
<html>
<head><title>….</title></head><body>
<div class=”header-content”>@RenderPage(“~/shared/_Header.cshtml”)</div>
<div class=”body-content”>@RenderBody()</div>
<div class=”header-content”>@RenderPage(“~/shared/_Footer.cshtml”)
</div>
</body>
</html>

Points to Remember :

  • The layout have only contain one RenderBody method, but can have multiple sections.
  • RenderSection runs code blocks which we define in our content pages.
  • RenderPage method is used to render other exists view in our application.

Bundling and minification

From which version ?

We can use Bundling and minification from ASP.NET 4.5 (ASP.NET MVC 4). In MVC3 and Asp.Net 4.0 application we can utilize by including System.Web.Optimization.dll and WebGrease.dll reference to our projects  and we can create the bundle for .css and .js files with in the Global.asax file.

What is it?

Bundling: It’s a group of js and css files that could be referred by unique name.
Purpose: The main usage of bundling is, it being loaded with one HTTP request instead of multiple request for each file.

Minification : It’s main process is removing of unnecessary white-space from the js and css files.
Purpose: The main purpose is to remove line break and comments from code and improving load times by reducing its size of the file.

Work with Example: 

Let we start to discuss with the simple example of working process for bundling with js files.

Example 1: Without Bundling

Step :1

In our example, i had referred five following script files in the “index.cshtml” view.

<script src="~/Scripts/jquery-1.8.2.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
<script src="~/Scripts/jquery.validate.js"></script>
<script src="~/Scripts/knockout-2.2.0.debug.js"></script>
<script src="~/Scripts/knockout-2.2.0.js"></script>

Step :2

Run the application and see the output for the request in browser as shown below. Each files request make their own time. Totally they spend 513 millisecond to load all files(ie., 0.513 seconds).

From the above image, we understood the page request five time for loading script file . To reduce this loading time we have moving to bundling concept. Let we dicuss with sample exmple

Example 2: Using Bundling

Step :1

Instead of refering all the files in view, we moving them together in BundleConfig.cs file in App_Start folder like below

public class BundleConfig
{
public static void RegisterBundles(BundleCollection bundles)
{

bundles.Add(new ScriptBundle("~/bundles/dotnet-helpers-scripts").Include(
"~/Scripts/jquery-1.8.2.js",
"~/Scripts/jquery.unobtrusive-ajax.js",
"~/Scripts/jquery.validate.js",
"~/Scripts/knockout-2.2.0.debug.js",
"~/Scripts/knockout-2.2.0"));

//For adding css use below piece of code. Add css files after removing all white-space and line break to achieve minification

bundles.Add(new StyleBundle("~/Content/css").Include("~/Content/site.css"))
}
}

All the files has been included under the unique name dotnet-helpers-scripts.so if we want to call these all js files in view, then we will call using bundle file name “dotnet-helpers-scripts”

Step :2

Be aware these two things has been included in Application_Start method in Global.asax file in the application

protected void Application_Start()
{
BundleTable.EnableOptimizations = true;
BundleConfig.RegisterBundles(BundleTable.Bundles);
....
}

Step :3

Here we calling the bundle dotnet-helpers-scripts which contain all 5 files. So here the request will only once while site loading

@{
Layout = null;
}

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
@Scripts.Render("~/bundles/dotnet-helpers-scripts")
</head>
<body>
<div>
<h1>Bundling in dotnet-helpers.com</h1>
</div>
</body>
</html>

Step : 4

Run the application to see the output difference using browser debugger mode

Form above image, all files are bundled in one (ie., dotnet-helpers-scripts). Instead of loading five .js files, it has been loaded with single dotnet-helpers-scripts bundle. so its taking only 63 millisecond (0.063 second) to load.

Minification :

In same way we can also include the .css files in bundling. We need to remove all the white-space and commands as shown in below example

Example:

body{background-color: #fff;border-top: solid 10px #000;color:#333;font-size:.85em;font-family:”Segoe UI”, Verdana,Helvetica,Sans-Serif;margin:0;padding:0;}…..

For css we use @Styles.Render(“….”) instead of @Script.Render(“….”) and  bundles.Add(new StyleBundle(“~/Content/css”).Include(“~/Content/site.css”)) instead of  bundles.Add(new ScriptBundle(“~/bundles/jquery”).Include(“~/Scripts/…”));

Keep cool coding….

Different ways of rendering layout in MVC

What is Layouts?

Layouts is same like as form which may used commonly among all the pages. Layout are like Master page in web form.

What is the use?

Using Layouts, we can maintain consistent look and feel across the pages/views within our site/application. It contains common html,css,content…

Rendering layout in different ways :

Let we discuss about the different ways of rendering layout in our forms.

Render Layout 1 : Mention Layout with in each view on the top

The default layout has been added while creating the view. We can override the default layout by assigning our own layout like as shown below

@{
Layout = “~/Views/Shared/_CustomerLayout.cshtml”;
}

Render Layout 2 : Returning the Layout in controller –> ActionResult

Here we can override default layout by rendering the layout from the ActionResult. From below code, the layout _customerLayout has been replaced in the Index view.

public ActionResult Index()
{
….
return View(“Index”, “_CustomerLayout”, model);
}

Render Layout 3 : Define _ViewStart in each Folder/directory

We can set default layout for particular directory/folder by creating _ViewStart file in each of the directories/folder with the piece of code as shown below

@{
//Name of the Layout which want to be set as default
Layout = “~/Views/Shared/_Layout.cshtml”;

}

 

After creating _viewStart.cshtml in each directory, it will be set as default layout while creating new view in the same directory.

Keep cool coding….