Introduction
For a MVC beginners it not that easy to find a simple article where he can scratch start his MVC journey. I do even faced the same problem. So i learned from various source the finally i am writing this article so that one can find it too easy to start with MVC. This article demonstrate the basic Add, update and delete functionality using Entity to SQL and MVC.
Background
Before we start with this article i advise you to read a tip "Entity Framework - Sample Application for Beginners". I found this article very helpful as we are also going to use entity to Sql in this project. The reason i choose this approach is you need not to worry about creating models, thus lots of time will be saved. Although changes in database and updating models accordingly is also easy in this approach. For the simplicity i will use the same database as used in that project/article/tip. So, Asp.Net web Form and Entity Framework basic knowledge is all required to start this tutorial.
What is MVC ?
MVC is nothing but an development pattern designed to separated the application into three parts which are communicating to each other t give us a ready to use application. The three parts are:
- Model : It works as the data access layer to the application. It is nothing but simple class which have already used in asp.net web forms.
- View : It works as the presentation layer (UI layer) for the user. We write our HTML's here basically.
- Controller : It works as the business logic layer for the application. When ever a user makes any request, the request ends here and this in reply provide user a view using models.
This was the basic of MVC. Its very simple. isn't it? So Without further adieu...let's start with our first project. All the best !!
Using the code
Hope you have undergone that article ("Entity Framework - Sample Application for Beginners") as will using that same data base. This article is prerequisite.
Now, let's start by Create New MVC 4 Application (i am using MVC 4). Here are the walk through :
1. Create Project > Visual C# MVC > ASP>NET MVC 4 Web Application
Give it a name and then save click 'OK'
2. Choose project template. You can choose any template as per your requirement, but lets choose 'Internet Application' as it gives the ready made basic template whiz very helpful for a novice.
Leave the View engine as Razor. (One of the default view engines provided by MVC) . Click 'OK' and you will be ready with your template. You can run it to test if its working or not. I am sure i will be working. So let's move on.
3. First Screen with ready-made Template: Here the some details about you first screen of MVC project.
Now if you focus on the right 'Solution Explorer' you will find some folder created in here. The are because we choose the internet template for the project. Here all the three layers of application (Models, Views and controllers) are separated to different folders and kept isolated to each other. Here is the detailed view of it.
Now lets have a view of out left section of our Home controller. This is very important section of our project as most of the time we will be working in this section to implement out business logic. Every method in this section will perform its own operation which is independent of other and gives us a view.
Now you can make changes in the lines written in Index, About or Contact methods you will your changes will reflect on views.This was basic. But we will not be using MVC application by hard coded data. So let's bring the database in the play.
4. Create Database (MS SQL SERVER) And Entity Data Model.
You can create the database by running the script as provided in here ("Entity Framework - Sample Application for Beginners") . If you have not created yet, please go to this article and create the database and perform the following actions from that article
1. Create Database
2. Create entity Data model (perform all 7 action).
Note: As we already have model folder here, please add the data model in Models Folder to keep things organized. done, you are ready with your Model as 'LearnEF.edmx
'. When you explore this file, you can find you employee table entity model in there and you will see all the column as the property in the model.
Please build you project so that you can have the reference to the models available in you project.
Please Note : We are using that article as base so that we can save our time to rewrite that part and also to keep our article focus on MVC only.
5.Add Controller : Now lets add our first controller.
- Right click the controllers folder >> select Add >> select '
Controller'
- Enter the controller name you want. (i give '
FirstController
'). Please keep 'Controller
' word as post fix to your controller. In template select 'Empty MVC controller
'. Click Add. Now you can see it will have a default method Index().
- Good practice is left the index method as write the code you need to execute as you do in page_load in web forms.
- Please include the 'Model' namespace in your project using as we are using the 'Employee' model this created in 4th step. Just add this line to your controller's using block
using StartWithMVC.Models;
6. Add View: Now add our first view
Right click the first line of the Index method (public ActionResult Index()) >> Add View
Now in Add View window give a name to view (i gave 'Index'
i.e. default). Now as we are saving or updating our Employee table in data base and for that we have added the 'Employee' model using Entity Data Model earlier in step 4 , let's make this view of type 'Employee' model.
Making view strongly Typed : Just add the following line as first line in the view to make it strongly typed for employee model.
@model StartWithMVC.Models.Employee
Now lets create our form with edit fields for the column of our employee table to take input using Model. To do this use the following lines of code:
@model StartWithMVC.Models.Employee
@{
ViewBag.Title = "SaveEmployee";
}
<h2>SaveEmployee</h2>
@using (Html.BeginForm("SaveEmployee", "First"))
{
<fieldset>
@Html.HiddenFor(m => m.EmpId)
<p>
@Html.LabelFor(m => m.HREmpId)
@Html.TextBoxFor(m => m.HREmpId, new { maxlength = 10 })
</p>
<p>
@Html.LabelFor(m => m.FirstName)
@Html.TextBoxFor(m => m.FirstName, new { maxlength = 30 })
</p>
<p>
@Html.LabelFor(m => m.LastName)
@Html.TextBoxFor(m => m.LastName, new { maxlength = 30 })
</p>
<p>
@Html.LabelFor(m => m.Address)
@Html.TextBoxFor(m => m.Address, new { maxlength = 30 })
</p>
<p>
@Html.LabelFor(m => m.City)
@Html.TextBoxFor(m => m.City, new { maxlength = 30 })
</p>
</fieldset>
<input type="submit" name="btnSave" value="Submit" />
}
Description of Razor View Engine Code:
Although this article is about MVC but we will use Razor View Engine, so basic knowledge of Razor View Engine is prerequisite.
- '@model' : This tell the razor that this view is strongly typed for model mention following this. Now when we submit the form it will pass the object of its Model type. So we can on controller get this object and retrieve the details enter for the model properties. You will see later how we do this.
- @using (Html.BeginForm("SaveEmployee", "First")) : This tell Razor that we are creating a form that will call the '
SaveEmployee
' method upon submission which is in the 'First
' controller. i.e. 'FirstController
'. - @Html.HiddenFor(m => m.EmpId) : Creates hidden field for unique id of our EmpID column in database using
EmpId
property of the model as included in first line. - @Html.LabelFor(m => m.HREmpId) : Create label to display for
HREmpID
property of the model. It display the property name(whiz column name). We can change it if we want or we can hard code it. That's your wish. - @Html.TextBoxFor(m => m.HREmpId, new { maxlength = 30 }) : This creates the
textbox
for HREmpID
property and here i specified additional parameter to this as new { maxlength = 10 }. You can specify as many property (html attribute) for this text box as you want. - finally we have button to submit the form, and in last we closed the braces to tell this is the closing tag for the form.
7. Write Action in the Controller For 'SaveEmployee' :
Now, write the following statement in your controller for the save employee action. You can see the code written in this section is same that mentioned in reference article to save new record in data base using entity model.
Note: Here our view was strongly type for Employee model so it pass used filled enteries as property value to the employee object ObjEmployee
and further entity framework code is used to save that data.
Now build and run you project and enter values in the fields and press submit. That is it, just check you database and you will have the entry in database.
That's all about how to perform a basic save operation with MVC. For Display, Edit and delete stay tuned..
Points of Interest
- So here how we saw how Controller and View communicate to each other with Model as intermediate. When the user request a url, the request comes to the controller and Controller using Model display a strongly type view.
- Then user input the data and submit the form, thus view returns the object of Model with input values assigned as its property.
- The controller then process the data using this object and in response return a view.
- A very smart razor view engine reduces you efforts to smartly writing the html for you.
Continued...
This is part-1 of this series . Part 2 will have Update, Delete and Listed display of saved record.