Category Archives: General

MVC Strongly Typed Views

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

Using ViewData / ViewBag in ASP.NET MVC applications is an easy way to pass data between controller and view but it is not a good practice. Read this article for further details.

In order to eliminate the inefficiencies of the ViewData / ViewBag we will make the View a strongly typed View based on a model selected. In order to do that, we need to add a @model directive on top of our view class (MyAction2 on the demo application. Read more about our demo application if you need.)

@model MVC_DemoApp.Models.Demo

In our demo application, view has the following line of declaration for the customers:

@{
 ViewBag.Title = "MyAction2";

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

And we were referencing the customers entries like:

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

 

After making our view a strongly type view we change the way how we display the customer data as follows:

 

@model MVC_DemoApp.Models.Demo

@{
ViewBag.Title = "MyAction2";
MVC_DemoApp.Models.Customer[] customers2 = Model.customerList();
}

---

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

 

By this way we skip using the ViewData / ViewBag and we dont make any type conversions.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Advertisements

MVC Part Three (Views)

This is the second 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 of the tutorial series, we will concentrate on the Views and the organization of the UI elements.

Views

Views are one of the complicated parts of the MVC architecture and they serve as the user interface (UI) layer for the application.

In order to add a view to our application, we have some alternative approaches. First of all, we need to decide weather our new view will be dedicated to a specific controller or will be a common view that may be used more than one purpose.

Shared views are placed in a folder named “Shared” just under the “Views” folder. If the view will be associated to a specific controller, we need to put it in a folder named as the controller name (without Controller sufix) under the Views folder.

In either way it is important to notice that Asp.Net MVC views and controllers are not tightly coupled. One action method can refer more than one view and one view can be referred by more than one action method (on the condition that it is placed under the Shared folder).

Creating a View (Method 1)

Create a folder named “Shared” under the “Views” folder (if it is not already present). And right click to Shared folder and select Add>View to create a view named “SharedAction” as shown below.

30

By clicking Add button, a new file “SharedAction.cshtml” is placed in the Shred folder. This simple file looks like this:

@{
ViewBag.Title = “SharedAction”;
}

<h2>SharedAction</h2>

Creating a View (Method 2)

This is an easier way of creating a view. If you remember that we had a DemoController class previously created in our MVC_DemoAPP, we can right clik our MyAction() action method name and click “Add View” option.

Entering a view name and clicking the Add button will be enough for creating the specific view as show below. Here, change the view name to MyAction2 since MyAction view has been already included in our demo app. (In this way, view is located in the specific folder in Views folder having the same name with the Controller.)

32

We have previously said that views are the UI part of the MVC architecture and the default expected UI candicate for web applications be the HTML output. The content of the SharedAction view is far away from a complete HTML syntax. As you probably know, even some basic structure is not defined like <html>, <body> etc.

_Layout.cshtml

At this point we nedd to talk about a special view that is called as the Layout view. ASP.NET MVC has a Layout view that contains common UI components, to prevent repetition of the common code in every page. This layout view is same as the master page of the ASP.NET webform application. Since that view is a common container and will be shared among other views, it is located in the Shared folder in the Views folder.

The layout view allows you to define a common site template, which can be inherited in multiple views to provide a consistent look and feel in multiple pages of an application. The layout view eliminates duplicate coding and enhances development speed and easy maintenance.

If you open the Layout view you see that the layout view contains html tags, head, body etc as the normal html. But if you look at closer, you see that some non html code exists in it. Among them the most important one is the RenderBody() method. RenderBody acts like a placeholder for other views. The content of the other views like SharedAction view  will be rendered in to the layout view, in the palce where the RenderBody() method is being called.

_ViewStart.cshtml

As for the master pages in ASP.NET WebForm applications, ASP.NET MVC applications may have one ore more than one layout views defined. The default layout view is specifid in the “_ViewStart.cshtml” file in the Views folder. That file is included in the Views folder by default ant ist contents look like that:

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

As you see, it is a simple file, just setting up the layout page to the defaults. It sets all the views in the Views folder and sub-folders to the defult layout. In the sample code (_ViewStart.cshtml), the Layout property is set to “~/Views/Shared/_Layout.cshtml”.

THis means, “_layout.cshtml” would be layout view of all the views included in Views and its sub-folders. This means, all the views derived the default layout page from _ViewStart.cshtml of Views folder.

One important feature is that the _ViewStart.cshtml can be included in any sub-folder of View folder to set the default layout page for all the views included in that particular sub-folder only.

A new layout page can be created simply right clicking the Shared folder in Views folder and selecting the Add>New Item menu from the dialog and selecting MVC Layout Page under the MVC part of the Web templates as shown below.

31

Setting Layout property in individual views

We can also override the default layout page set by _ViewStart.cshtml by setting Layout property in each individual .cshtml view files. The following code snippet shows how to change the default layout for a particular view:

@{
ViewBag.Title = “My Page”;
Layout = “~/Views/Shared/_myCustomLayoutPage.cshtml”;
}

Specify Layout page in ActionResult method

We can also specify which layout page to use while rendering the view from action method using View() method. The following code snippet, the View() method renders Index view using _myCustomLayoutPage.cshtml.

public ActionResult Index()
{
return View(“Index”, “_myCustomLayoutPage”);
}

Rendering Methods

ASP.NET MVC layout view renders child views using the following methods.

Method Description
RenderBody() Renders the portion of the child view that is not within a named section. Layout view must include RenderBody() method.
RenderSection(string name) Renders a content of named section and specifies whether the section is required. RenderSection() is optional in Layout view.

RenderBody() method is simply where all the content of the guest view is rendered in the Layout view. If the so-called guest view has some contents that is marked vy @section definition, RenderSection(string name) method is the place where these marked content is rendered in. Notice that, the @section defined parts are omitted while rendering by the RenderBody() method.

@section <section-name> definition block starts from the definition line and continues until another @section definition or the guest layout ends.

 

So far so good 🙂 In the next part, we are goingto focus on the models and after that we wil put all together to see a woring example.

 

References:

  1. http://www.tutorialsteacher.com/mvc/layout-view-in-asp.net-mvc

 

 

 

 

 

 

 

 

 

 

MVC Part Two (Controllers and Basic Concepts)

This is the second 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.

MVC is a software architecture that separates business logic from the  user interface. This is done by separating the application into three parts: the Model, the View, and the Controller.

The model is the business logic, the view is what the user see on their client device and the controller is the mechanism that serves in between them. It receives user request and perform appropriate actions.

After this brief explanation, one can easily understand why the application we created in the part one is not working properly.

ASP. NET MVC Controllers

Controllers are the mechanism for handling the user’s requests. User requests are  processed by the controllers and required actions are taken accordingly and users have responses. The most common response is an HTML output but many other types of responses can be produced.

For the newly created application in part one, we had an error message since we have NOT defined any controlers yet.

Open the MVC_DemoApp and add a new Controler as follows:

  • Right click on the Controllers folder in the solution explorer and click Add, select Controller.

5

  • Select MVC 5 Controller – Empty and press Add. Give the name as DemoController and press OK.

6

In this step do NOT delete the Controller part of the name since it is IMPORTANT for the convention.

7

In ASP.NET MVC, the name and the location of the object is important since the organization of the components are based on them.

By creating the DemoController, a class named as DemoController.cs is located under the Controllers folder. DemoController is the class name of the controller and the Demo is the name of the controller.

The code below is created automatically in the DemoController class.

namespace MVC_DemoApp.Controllers
{
public class DemoController : Controller
{
// GET: Demo
public ActionResult Index()
{
return View();
}
}
}

We have a public method called Index() in the DemoController class. Each public method in controllers is become action methods automatically. Action methods accepts user’s request and returns some response. To make a method not an action method, it must be defined some access modifiers other than public (like private etc.) or we need to add an [NonAction] attribute on top of the method if the method must be public like:

[NonAction]
public string SimpleMethod()
{
return “I am NOT an action method anymore :(“;
}

Another intresting and important thing in the Index method above is its return type. Our Index method has the return type of ActionResult and returns a View method that creates a ViewResult object which renders View to the response.

ActionResult is the abstract class and ViewResult is the child of ViewResultBase and ViewResultBase is the child of ActionResult.

ActionResult <- ViewResultBase  <- ViewResult

To keep the polymorphism in action, out Index method has the return type of ActionResult since some other result type (like Content Result) may be returned based on some criteria from the same action method.

For now, we will NOT return a View or Content. We will just return a message to the user that the request has been taken by the server. We will replce the Index method by the following MyAction method that will simply returning a string object:

public class DemoController : Controller
{
// GET: Demo
public string MyAction()
{
return “User request is handled by MyAction Method…”;
}
}

Run the application (press F5) and see the result.

4

Wowww.. This is not what we wanted to see.

What has just happened is, we make a request from our application without a controller name and an action name. Therefore our application is used the default values for the controller and the action names which are specified in the RouteConfig.cs under the App_Start folder.

RouteConfig.cs has the following line of code in it:

public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute(“{resource}.axd/{*pathInfo}”);

routes.MapRoute(
name: “Default”,
url: “{controller}/{action}/{id}”,
defaults: new { controller = “Home“, action = “Index“, id = UrlParameter.Optional }
);
}
}

The code marked as red are the names and the code marked as green as the values. The default controller name is Home, and the default action name is Index. When we run the application without specifying any of them these defaults are used.

In order to run our application as expected we need to specify the controller name and the action name as the “{controller}/{action}/{id}” convention.

Change the url of the browser: http://localhost:xxxxx to http://localhost:xxxxx/Demo/MyAction in order to activate the correct action while the application is still running. (If you have stopped VS IDE, you need to run the application again)

 

Up to this point, out basic MVC application now working and serving a simple text message to its users.

On the following parts, we will expand our capabilities and dig in more details…

 

References:

  1. http://www.codeproject.com/Articles/866143/Learn-MVC-Project-in-days-Day

 

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