Category Archives: MVC

MVC ViewData & ViewBag

This article is a case study which you may need to read a general information about MVC first. Click here for basics.

ViewData is simply a dictionary composed of key / value pairs, which will contains data to be passed between controller and views. Controller will add the items to this dictionary and view reads from it.

While ViewData is an easy to use collection of data it holds objects internally. When a new value is added into the ViewData, it gets boxed to object type. So unboxing is required every time we extract values out of it.

On the other hand, ViewBag is just the dynamic representation of ViewData. ViewBag uses the dynamic feature of C# 4.0 and makes ViewData dynamic. From the definition it is clear that ViewBag internally uses ViewData.

We can add data to ViewData and read it from the ViewBag and the Vice versa is also possible.

While ViewData and ViewBag is an easy way for passing values between Controller and Views it’s not a good practice to use any of them.

First of all, data stored as Object type in ViewData so we need to have conversions every time we want to use it. This is a performance issue and more than that, it may result in wrong type of conversion and open to runtime errors.

Another major disadvantage is, as the controller and view are loosely coupled they both are unaware about what’s happening inside of them so incorret values from the controller may be passed to the ViewData/ViewBag and therefore to the View leads into run time issues and inefficiency in development.

 

References:

http://www.codeproject.com/Articles/897559/Learn-MVC-in-days-Day

 

MVC Part Four (Models)

This is the fourth part of the tutorial series about MVC.

In the first part, we have dig into a quick start of creating an empty ASP.NET MVC application and defined some basics. In this part, we will try to explain the mechanism of MVC and make the previous example work for the first time.

In the second part, we have given some basic definitions and information about controllers, what they are and how they work.

In the third part, we have concentrated on the Views and the organization of the UI elements.

In this part, we will talk about the model concept. A Model is a business specific portion of the MVC architecture, isolated from the other components.

A model is simply a class which holds all the required bussiness logic for the application. A model can be added to the project simply right clicking the Models folder and selecting Add>Class option.

Add a class named Demo.cs and change its contents with the following code.

33

namespace MVC_DemoApp.Models
{
 public struct Customer
 {
 public int customerID;
 public string customerName;
 public string customerCountry;

public Customer(int customerID, string customerName, string customerCountry)
 {
 this.customerID = customerID;
 this.customerName = customerName;
 this.customerCountry = customerCountry;
 }
 }

public class Demo
 {
 public Customer[] customerList()
 {
 return new Customer[]
 {
 new Customer(customerID: 1, customerName: "David", customerCountry:"ENGLAND"),
 new Customer(customerID: 2, customerName: "Michelle", customerCountry:"GERMANY"),
 new Customer(customerID: 3, customerName: "Laura", customerCountry:"GERMANY"),
 new Customer(customerID: 4, customerName: "Eva", customerCountry:"FRANCE"),
 new Customer(customerID: 5, customerName: "Nancy", customerCountry:"ENGLAND")
 };
 }
 }
}

 

This is for the model layer of our MVC Demo Application. Now lets combine all the things to have a working sample of an MVC application.

Open the DemoController in the Controllers folder and add the following action method which return the MyAction2 view:

 public ActionResult MyAction2()
 {
 return View("MyAction2");
 }

Run the application and type the URL as: localhost:xxxxx/Demo/MyAction2

This will bring the default layout of MyAction2 view to the screen. In order to show the Customer data there ase several ways to bring model data to the controller and pass it to the view.

For simplicity we will use ViewData which is a dictionary, that will contains data to be passed between controller and views. Controller will add items to this dictionary and view reads from it.

Add a using directive to the DemoController.cs for the model as:

using MVC_DemoApp.Models;

Modify action method MyAction2 as follows:

public ActionResult MyAction2()
{
ViewData[“Customers”] = new Demo().customerList();
return View(“MyAction2”);
}

To display the customers in ViewData[“Customers”] modify the MyAction2 view as follows:

@{
 ViewBag.Title = "MyAction2";

MVC_DemoApp.Models.Customer[] customers =
 (MVC_DemoApp.Models.Customer[])ViewData["Customers"];
}

<h2>MyAction2</h2>

<table>
 <thead>
 <tr>
 <th>Customer ID</th>
 <th>Customer Name</th>
 <th>Customer Country</th>
 </tr>
 </thead>

<tbody>


 @foreach (MVC_DemoApp.Models.Customer c in customers)
 {
 <tr>
 <td>@c.customerID</td>
 <td>@c.customerName</td>
 <td>@c.customerCountry</td>
 </tr>
 }

</tbody>

</table>

 

In the code block presented above, we have used razor (@) syntax to get the customer information embedded in view. We will explain that later but for now just run the application and see the result as the following:

34

That is the end of the basic concepts and brief explanation of MVC and how it is working. Be creative and dont be shy to go into details and create similar projects to get used to the basics…

 

 

 

 

 

 

MVC Part One (Quick Start)

In this tutorial, we are going to create an empty ASP .NET MVC Web Application from the beginning and give some brief explanations for the related components. In order to create the project, Microsoft Visual Studio 2015 Community Edition is used for the development IDE.

Let us start with and empty project.

  • Open Microsoft Visual Studio 2015 (VS in short). Use File>New>Project (or Ctrl+Shift+N) to open New Project dialog. Select Templates>Visual c#>Web>ASP.NET Web Application and give the name as MVC_DemoApp

1

  • Select <Empty> template and check MVC in the Add Folders and Core References section. Press OK to create project template.

2

  • By pressing OK, VS has created some files and folders under the project template. The following layout is what we have right now.

3

App_Data folder can contain data files like LocalDB, mdf, xml files and other data related stuff. This folder is not served by IIS.

App_Start folder can contain class files which will be executed when the application starts. Typically, these would be config files like AuthConfig.cs, BundleConfig.cs, FilterConfig.cs, RouteConfig.cs etc. MVC 5 includes BundleConfig.cs, FilterConfig.cs and RouteConfig.cs by default.

Controllers folder contains class files for the controllers. Controllers handles users request and returns a response. MVC requires the name of all controller files to end with “Controller“.

Models folder contains model class files. Typically model class includes public properties, which will be used by application to hold and manipulate application data.

Scripts folder contains script files as the name implies for the application. There are many script files in this folder. Each may be given in more detail in the following tutorilas.

Views folder contains UI (html) files for the application. Views folder includes separate folder for each controllers. Shared folder under View folder contains all the views which will be shared among different controllers e.g. layout files.

AppliacationInsights.config file provide settings for telemetry modules and initializers for automatically tracking telemetry from your application and its context. By adjusting the configuration file, you can enable or disable telemetry modules and initializers, and set parameters for some of them.

Global.asax allows you to write code that runs in response to application level events, such as Application_BeginRequest, application_start, application_error, session_start, session_end etc.

Packages.config file is managed by NuGet to keep track of what packages and versions you have installed in the application.

Web.config file contains application level configurations.

 

By the ent of the part one of the tutorial, we have the basic understanding of the related components and how to create an empty project template. So far the project is not complete and running the application will generate the following error:

4

Keep on reading the next parts to complete the project…

 

References:

  1. http://www.tutorialsteacher.com/mvc/mvc-folder-structure
  2. https://azure.microsoft.com/tr-tr/documentation/articles/app-insights-configuration-with-applicationinsights-config/
  3. http://www.techjunkieblog.com/2015/04/aspnet-mvc-5-create-aspnet-mvc-5-empty.html