In this article we will learn how to create a basic application in MVC 4 using Razor.
Step 1: Create a new project then select "Visual C#" then inside that select "ASP.NET MVC 4 Web Application".
Enter the name as "MyfirstMvcApplication".
Click "OK". A new windows will pop up like this:
Select Internet Application
View engine: Razor (because we will use Razor syntax for coding).
Step 2: After the project is created successfully like this a screen will appear as in the following:
Now in the solution you will see a folders named "Controllers", "Views" and "Models" that are created by default with some files inside them.
Now let's start to add a controller.
Right-click on the "Controller" folder and select Add from list and then you will see controller, select it.
After clicking on Controller you will see a popup window like this.
With default name. [DefaultController]
When giving a name to the Controller the word "Controller" should be suffixed always.
I am giving the name MyHomePageController.
After providing the name click the "Add" button.
After this step you will see a Controller created.
With the default method
Index ()
In this step I will change the Method name
Index to
MVCHome.
Add a View to the Controller in this step.
Right-click on MVCHome.
Select
Add View.After adding a view you will see a new window.
In this window you will see View Name that will be the name of the method on which you right-clicked.
There is a dropdown list named View Engine in Razor selected as the default.
And check box create a strongly-typed view that is disabled.
Use a Layout or Master page that is checked by default.
Uncheck that.
Click on the "Add" button.
.
After adding the view a folder with the controller name is created and inside that a view with the name "MVCHome" with the extenstion cs.html.
After this in the Controller I will use Viewdata and a ViewBag to display a message in the View that we created.
What ViewData and ViewBag are
1. ViewData and ViewBag are used to pass data from a controller to the corresponding view.
public ActionResult MVCHome()
{
ViewData["MyData"] = "My First Mvc Application WOW";
// Declaring ViewData like this
ViewBag.Mydata = "My First Mvc Application WOW";
// Declaring ViewBag like this
return View();
}
Now we will move from the Controller part to the View part.
In the View Part we will display a message stored in the Viewbag and ViewData using Razor Syntax.
Razor syntax begins with @ { }
Using @: to explicitly indicate the start of content.
After this just run your application.
You will see something is the default page.
To call the view page:
Final Output
We have completed our first tutorial, Wow.
Any issues or problems then just comment on the article to get solutions.