November 7, 2012

Add a View to Asp.Net Mvc

In the previous post, I showed how to add a Controller to an Mvc project. As you could see, html rendered in the page was done by Controller. In this post, I will show how to add a View to an Mvc project. The View is more like a template that can generate html output to the user. For this example, I have used Razor as the View engine.

The Demo Controller class created in the previous post looks like below.

Controller
  1. public class DemoController : Controller
  2. {
  3.     public string Index()
  4.     {
  5.         return "You are viewing Index method of DemoController";
  6.     }
  7.  
  8.     public string Home(string name, int age)
  9.     {
  10.         return "Hello " + name + ". You are " + age.ToString() + " years old";
  11.     }
  12. }

Now, I will add a new method – Welcome that will return the View.

View
  1. public ActionResult Welcome()
  2. {
  3.     return View();
  4. }

To create a View, right click on method name and Add View.

1

2

Note that, I have left the default settings and names. The default View has the following code.

Welcome View
  1. @{
  2.     ViewBag.Title = "Welcome";
  3. }
  4.  
  5. <h2>Welcome</h2>

I have added some message, so the code will look like below.

Welcome View
  1. @{
  2.     ViewBag.Title = "Welcome";
  3. }
  4.  
  5. <h2>Welcome</h2>
  6. <p>This is a demo welcome page</p>

When the page is run, it looks like below.

Welcome - My ASP.NET MVC Application 2012-11-06 17-24-18

0 comments:

Reference: Shahed Kazi at AspNetify.com