Simple MVC and Razor with Database Connection for Simple Insert, Update and Delete.

Model View Controller

If you are new in MVC (Model View Controller) then this tutorial is the ideal for you. I had issues in finding one single tutorial with all my questions so I decided to put one together myself. This tutorial might seem long however, most of the tutorials is full of images to help you visualize better so in order words, it is not as long as it might look like on your scroll bar ;) Goodluck and hope you find no issues… if you do, feel free to leave a comment and I will be glad to help where possible.

Step 1: Create an MVC project

If you do not already have MVC 4, download the latest version HERE

Open Visual Studio 2010 >> File >> New >> Project

From the left side panel (Templates) Select: Visual C# >> Web >> ASP.NET MVC 4 Web Application

1.New-Project-Web-MVC.fw

From the pop-up window, select Internet Application from the templates and select Razor as a View Engine as shown below:

MVC razor

Step 2:  Overview 

Visual Studio will create a project containing the following files and folders:

Application information: Properties, References

Application folders:  App_Data Folder (ex. DB),

Content Folder (ex.CSS, images),

Controllers Folder (classes responsible for handling user input and responses / Code behind) (All classes names have to end with Controller.cs)

Filters Folder (not required for this tutorial)

Models Folder (classes to represent application models to contain and manipulate application data such as business logic, data access logic, validation, logic, etc),

Scripts Folder (ex. Javascript Files, Jquery),

Views Folder (User Interface) (For each class in controller, you should have a folder in Views) (ex. html, aspx, cshtml etc)

Configuration files:  Global.asax,  packages.config, Web.config

It should like something like this:

MVC project folders

Step 3: Design

It is time to create a design for our testing website by editing our Layour. With razor we do not use a MasterPage but we use a _Layout.cshtml page :

Expand the “Views” folder >> Expand the “Shared” folder >> Open “_Layout.cshtml”     (further down there are few tips on editing a razor syntax page)

To Edit the CSS, we can either open the default created css file or create a new one from:

Expand the “Content” folder >> Open “site.css”  

– OR –

Right Click on “Content” folder >> ADD >> New Item 

Add New Item CSS

PS: the “Shared” folder under “Views” contains shared files between all other folders such as the “Home” and “Account” folder which have been created by default (see next image for visuals).

Step 4: Managing Controllers

We must first understand how controllers work. Controllers contain classes responsable for  handling user input and responses just like we used to use the code behind in a normal .NET application.

It is important to understand that web servers map incoming URLs with pages/files directly. In this case, MVC maps incoming URLs with methods in the controller classes. Therefore, controllers are responsible to process incoming URL requests, handle input, save data and send response back to client.

Each Class in the “Controller” folder requires a folder in the “Views” folder.

The Controller Class requires to define each control in the matching folder under “Views”. Each method would look similar to:

    public ActionResult About()
   {
        return View();
   }

4.Controllers

Now, if we open both the “HomeController” under “Controllers” and the “index.cshtml” page (this is a razor page) under “Views/Home” we can see the relation between the two:

So, lets test something small here…. in the “HomeController” lets add another ViewData to the Index() and also add a <%: ViewData[] %> somewhere in the “Index.aspx” as shown below:

5.Controller-Views

Now, Run the page in a browser (CTRL + F5) and you should see the text added there in place:

6.TestResult

Razor for cshtml tips:

To add a stylesheet or javascript reference to a page we use @Url.Content:

<link href=”@Url.Content(mySite.css”)” rel=”stylesheet” type=”text/css” />
<script src=”@Url.Content(“jquery.js”)”></script>

Declaring a variable to be used multiple times within the page by using the @ViewBag:

@{ ViewBag.Title = “Home Page” }

Using a variable which has been declared on the page by using the @ViewBag :

<h1>@ViewBag.Title.</h1>

Creating a Menu using the ActionLink:

@Html.ActionLink(“Home”, “Index”, “Home”)                    //First Parameter: Link Text       Second Parameter: Controller Action     Third Parameter:  Value to pass on to the new Page/Controller (ex.ID 3)

Step 5: Adding the Database to select, insert, update and delete data

Unless you have an existing Database, create a portable db for this tutorials sake:

Right Click on “App_data” >> ADD >> New Item >> SQL Database >> Name it “mvcDBs.mdf” >> SAVE

The Database “mvcDBs” should now be visible in your Server Explorer usually on the left side of the page.

Open Database >> Right click Tables >> Add new Table

Set the following columns: UserId int (primary ID and set auto increment by setting “Identity Specification” from No to Yes), UserFirstName nvarchar(50), and UserLastName nvarchar(50)

Save the Table with the name “Users”

7.Create-Users-Table

Now, add connection string to your web.config as usual and use the name as follows:    <add name=”mvcDBContext” connectionString=”  “>

Step 6: Adding A Data Model

Visual Studio should have created an AccountModels.cs automatically on project creation under the folder “Models”.

We need to add a Reference to System.Data.Entity and in some cases where this is not enough, we need to add reference to the EntityFramework.dll

If you do not have one already, you can download it from here copy to your bin and build or right-click References >> ADD >> Browse>> bin >> EntityFramework.dll :

http://www.rochellecassar.com/EntityFramwork_dll/EntityFramework.dll

Now lets create our own database model. Right-click the folder “Models” >> ADD >> New Item >> Web >> Class  >> Name it “User.cs”

Note that the table name it “Users” and the data model is named the same but without the “s” at the end, “User” which is the naming convension used for Data Models to connect with the actual table in the DB.

After setting all getters and setters, we need to add the DbContext and once finished, it should look somethink like this:

using System;

using System.Data.Entity;

using System.ComponentModel.DataAnnotations;

namespace MyFirstMVC.Models
{
public class User
{

[Key]  //Specifying that UserID is our Primary Key
public int UserID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }

}

public class mvcDBContext : DbContext
{
public DbSet<User> Users { get; set; }
}

}

P.S if you allowed nulls in the database make sure to state it. For instance if LastName can be null than you should write “public string? LastName”  or you will get an error in the next step.

Also, we need to add a Controller for this Model. So Right Click “Controllers” >> ADD >> Controller >> and name it “MyUsersController.cs”, select template and insert text as shown below:

9.Model Controller

Now you should have a controller “UsersController” under Controllers, while ALSO you should now have a new folder “Users” in the “Views” folder with the pages Create, Delete, Details, Edit and Index.

Click: Ctrl + F5 and add /Users to the URL to access the folder created. There you can view the data in the table, create rows in the Users table, delete, edit, etc.

Lets test this out:

Click on “Create New” under heading Index and you sould see a similar form… fill it up and submit:

10.Database

Now from the Server Explorer (If not visible go to top menu >> VIEW >> Server Explorer), open the database, find the “Users” table >> Right Click >>”Show Table Data”

11.Database-Result

Thanks for following and hope you enjoyed your first MVC project tutorial :)

//

About these ads

9 thoughts on “Simple MVC and Razor with Database Connection for Simple Insert, Update and Delete.

    • In the Database user add the following columns: ProfileImage (for the filename), ImageMimeType (for the mimetype), ImageData (for the actual image)

      In the User Controller, the Create HttpPost should look something to the following:

      [HttpPost]
      public ActionResult Create(User user, HttpPostedFileBase image)
      {
      if(ModelState.IsValid)
      {

      if (image != null)
      {
      user.ProfileImage = image.FileName;
      user.ImageMimeType = image.ContentType;
      int length = image.ContentLength;
      byte[] bufferedImage = new byte[length];
      image.InputStream.Read(bufferedImage , 0, length);
      user.ImageData = bufferedImage ;
      }
      db.Users.Add(user);
      db.SaveChanges();
      return RedirectToAction(“Index”);
      }

      return View(user);
      }

      Goodluck :)

  1. How to Store Images database and also perform all curd operations using ASP.NET MVC
    I am trying to some examples i am not getting the output,

    I am new to Mvc

    Gove me one simple example on this complete code for that

    please help me

  2. This is my sample data from database,

    ID Name ImageUrl

    1 a http://notous.blob.core.windows.net/images/1-9.jpg

    2 b http://notous.blob.core.windows.net/images/10_discount-150×150.jpg

    3 c http://notous.blob.core.windows.net/images/FB-button-341×341.png

    I want display this data not for same This ImageURL display as image in My view Using ASP.NET MVC,

    And also At the time of insert also after uploading the image save in database Like above(its possible???)

    please help me,I am new to this MVC

      • This is my code I can edit two image at the time of edit,,
        This is my actual code ,Edit multiple images successfully edited,

        1) At the time of Edit single image not edited

        [HttpPost]
        public ActionResult Edit(int id, Product collection, HttpPostedFileBase[] MultipleFiles)
        {
        Product p = db.Products.Single(e => e.TagID == id);
        //List blobs = new List();

        if (MultipleFiles != null)
        {
        foreach (var fileBase in MultipleFiles)
        {
        if (fileBase != null && fileBase.ContentLength > 0)
        {
        // Retrieve a reference to a container
        CloudBlobContainer blobContainer = _myBlobStorageService.GetCloudBlobContainer();
        CloudBlob blob = blobContainer.GetBlobReference(fileBase.FileName);

        // Create or overwrite the “myblob” blob with contents from a local file
        blob.UploadFromStream(fileBase.InputStream);
        }
        }
        //}
        List blobs = new List();

        foreach (var fileBase in MultipleFiles)
        {
        CloudBlobContainer blobContainer1 = _myBlobStorageService.GetCloudBlobContainer();
        CloudBlob blob1 = blobContainer1.GetBlobReference(fileBase.FileName);
        //p.Image = blob1.Uri.ToString();
        blobs.Add(blob1.Uri.ToString());
        }

        p.Image = blobs.ElementAt(0).ToString();
        p.Image1 = blobs.ElementAt(1).ToString();
        }
        // TODO: Add update logic here
        //p.Image = collection.Image;
        p.Name = collection.Name;
        p.Price = collection.Price;
        p.Description = collection.Description;
        //p.Image = collection.Image;
        // p.Image1 = collection.Image1;
        db.SubmitChanges();
        return RedirectToAction(“Index”);

        }

  3. Dear sir, i have visual studio 2010 i download mvc 4 but its cannot install it because it shows ” this product required visual studio 2010 sp1″ how to fix my problem

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s