MarkAFarrugia

Freelance Web Development in Malta

By

MVC 4 and Javascript/StyleSheets bundling

First of all I would like to welcome any first time visitors to my blog. Before I start this blog I would like to give a brief introduction to myself. My name is Mark Anthony Farrugia and, apart from being a Computing Teacher, I am a freelance web developer based in Malta, a small island in the Mediterranean. So now let me start this blog post :)

In this blog post I will cover one of the new constructs which have been introduced in MVC 4 which is bundling. Basically MVC provides a way to bundle a set of Javascript or CSS files into one single bundle.

The outcomes of this blog are

  1. Understand how ASP.NET MVC Bundles work

The prerequisities of this blog are

  1. Have some understanding of what is JQuery
  2. Have some knowledge on ASP.NET MVC

So let me start this blog. One of the main reasons why I have moved from the traditional ASP.NET to ASP.NET MVC is its tight integration with JQuery. When an ASP.NET MVC solution is created JQuery files are automatically added with the solution. You will note that the JQuery files, whenever a new solution is created, are placed in the Scripts folder. Whilst I am writing this blog the JQuery version which Visual Studio automatically adds is JQuery.1.7.1, as shown in Figure 1. You can overwrite the JQuery version by downloading the latest JQuery library from here.

Figure 1 - JQuery files in Solution

Figure 1 – JQuery files in Solution

One of the most important issues you will encounter whilst developing with JQuery is that you would have to make use of multiple JQuery libraries to meet certain objectives. Rather than adding the libraries one by one ASP.NET MVC uses what so called bundles to bundle all the similar JQuery libraries.

To show how these bundles work open the Layout.cshtml which acts as the MasterPage and which ASP.NET MVC creates in its template project, or open a MasterPage for an existing project which you have created. Scroll down to the end of the page and you should find the two lines of code shown underneath.

@Scripts.Render("~/bundles/jquery")
@RenderSection("scripts", required: false)

Let me first explain the first line of code shown in the above snippet. This line of code is ensuring that all the JQuery files which are contained in the JQuery bundle are rendered in HTML. Now how does Visual Studio know what is included in the JQuery bundle? You can find this information in the BundleConfig.cs which is found under the App_Start folder.

The underneath code is a code snippet of the BundleConfig file.

public static void RegisterBundles(BundleCollection bundles)
 {
 bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
 "~/Scripts/jquery-{version}.js"));
}

If you examine the above code you will note that the bundle is called “~/bundles/jquery” and this matches the first line of code (@Scripts.Render(“~/bundles/jquery”)) shown in the previous code snippet. This bundle includes one single JQuery file which is located under the Scripts folder as shown in line 3 and 4 in the above code snippet. Now run your project and at the end of your HomePage you should find the HTML shown in Figure 2.

Figure 2 - JQuery HTML in MasterPage

Figure 2 – JQuery HTML in MasterPage

So basically the @Scripts.Render(“~/bundles/jquery”) found in the Layout.cshtml just renders all the JQuery files found in the JQuery bundle specified in the BundleConfig.cs.

You should have noted in the above explanation that we have used the ScriptBundle class in the BundleConfig.cs to bundle Javascript files. MVC also gives you the opportunity to bundle StyleSheets and this is already done by the MVC Template project in the BundleConfig.cs. Noe that instead of the ScriptBundle the StyleBundle class is used.

bundles.Add(new StyleBundle("~/Content/css").Include("~/Content/site.css"));

To render the stylesheets in your page then you should use the underneath code. The above code works exactly as the @Scripts.Render. However rather then rendering JavaScript files which are located in a Javascript bundle, CSS files are rendered.

@Styles.Render("~/Content/css")

So basically in the above code snippet you are requesting .NET to render all CSS files found under the ~/Content/css bundle.

Finally let me explain what the code at line 2 in the underneath code snippet does. This code snippet was shown in a previous code snippet but I only gave an explanation for what code at line 1 does.

@Scripts.Render("~/bundles/jquery")
@RenderSection("scripts", required: false)

The above code snippet is found in the Layout.cshtml which acts as your MasterPage. Basically this line of code is rendering any Scripts section found in a child page which is making use of the MasterPage. For example, let’s assume that in your child page you want to use another JQuery library apart from the main JQuery library, which will be responsible for validating data. The underneath code will basically add the validation Javascript libraries found in the jqueryval bundle

@section Scripts {
 @Scripts.Render("~/bundles/jqueryval")
}

If you run your solution and open the child page which has the above code snippet, and then open the HTML which is rendered for this page you will find the HTML shown in Figure 3. You will note that first the main JQuery library is rendered, and then there are the scripts found in the JQueryval bundle.

Figure 3 - JQuery Validation Bundle

Figure 3 – JQuery Validation Bundle

I hope you found this blog post useful and till next time take care of yourselves :) .

By

Uploading Images in ASP.NET MVC

First of all I would like to welcome any first time visitors to my blog. Before I start this blog I would like to give a brief introduction to myself. My name is Mark Anthony Farrugia and, apart from being a Computing Teacher, I am a freelance web developer based in Malta, a small island in the Mediterranean. So now let me start this blog post :) .

The outcomes of this blog are to

  1. Discover how we can upload an image back to our server
  2. Understand when and how we can use IF conditions using Razor syntax
  3. Display a Product Image back in our View
  4. Understand how we can use the RedirectToAction and passing data back to out controller

The prerequisites of this blog are

  1. You should have a Products table which has a specific field of type Varchar which will store the image path
  2. You should have some understanding of LINQ To Entities
  3. You should have SQL Server Express installed. You can download it from here.
  4. You should have an Images and then Products subfolder in your project where we will be saving the uploaded image

In this blog I will be writing on how you can upload an Image back to a server using ASP.NET MVC. For those of you who are familiar with ASP.NET will find that the way this is done using ASP.NET MVC is somewhat different. In ASP.NET you would use the FileUpload control which takes care of most of the functionality.

So first things first. Let’s start by modifying our Edit Product View we have created in this blog. We will be adding an HTML form tag which basically is a form which posts back to a Controller action method which saves the image back to the server, and updates the relevant product with the image path. The Controller action method’s name is UploadProductImage and will accept a ProductId parameter. The underneath code snippet is the actual code which should be placed in our ASP.NET MVC View.

<form id="productimageuploadform" action="/Products/UploadProductImage" method="post" name="productimageuploadform" enctype="multipart/form-data">
  <input id="ProductId" type="hidden" name="ProductId" value="@Model.ProductId" />
 <input id="imguploadproductimage" title="Upload a product image" type="file" name="imguploadproductimage" />
 <input title="Upload image" type="submit" value="Upload" /></form>

Let me explain the above code. In the first line I am creating a form which posts back to the Products/UploadProductImage controller method. Note that a form which will upload an image should have the attribute enctype set to multipart/form-data. If this is not set the image will not be uploaded.

In the second line I am creating a hidden HTML field which stores the ProductId so that this will be passed back to our controller method. You will note that the Controller method has a single parameter also called ProductId. MVC will then map this hidden field value to the ProductId parameter inside the Edit Product controller method, since they have the same name. Recall that in this blog we created a Controller method which returns a single Product back to our Edit View. Thus I am using Razor syntax @Model.ProductId which basically returns the ProductId which is returned from our HttpGet Edit Product controller method.

In line 3 and 4 I am just creating an HTML input file control which basically will allow the user to select an image and a submit button which actually submits back to our Controller method.

Run your application and you should have a View as shown in Figure 1. Please note that this View is a continuation of the Product View we have created in this blog.

Product Upload Image View

Figure 1 – ASP.NET MVC which lets you upload a product image.

Let’s now create code for our UploadProductImage controller method, which the HTML form we have created posts to. This code is shown underneath. Basically in this code we are saving the image back to our server and then updating the existing Product with the image path on our server.

[HttpPost]
 public ActionResult UploadProductImage(Guid ProductId)
 {
 if (Request.Files.Count > 0)
 {
 try
 {
 if (Request.Files[0].ContentLength > 0)
 {
 HttpPostedFileBase postedFile = Request.Files[0];
 string filename = System.IO.Path.GetFileName(Request.Files[0].FileName);
 string strLocation = HttpContext.Server.MapPath("~/images/products");
 Request.Files[0].SaveAs(strLocation + @"\" + filename.Replace('+', '_'));
 Models.DBProducts products = new Models.DBProducts();
 Models.Product Product = products.GetProduct(ProductId);
 Product.ProductImagePath = @"\images\products\" + filename;
 products.EditProduct(Product);
 return RedirectToAction("Edit", new { id = ProductId });
 }
 }
 catch (FormatException ex)
 {
 return Content(ex.Message);
 }
 catch (Exception ex)
 {
 throw ex;
 }
 }
 return RedirectToAction("Edit", new { id = ProductId });
 }

So let me explain the code above. First of all note the method definition. The method accepts a parameter called ProductId which has the same name as our hidden field inside our HTMLform. You will be able to access the file uploaded using the Request.Files property.

On line 4 I am ensuring that there is at least one file and on line 8 I am ensuring that the file uploaded is not empty.

On line 10 I am getting the actual file uploaded as an HttpPostedFileBase class. I am then getting the filename of the file uploaded.

On line 12 I am getting the actual path where the image will be saved on the server. For those of you who do not know the Server.MapPath() basically returns the physical location on the server for a specific path. So for example, in our case we are getting the server physical path of the images/products folder. Remember that we need to transfer the file from the client pc to the server, and therefore we need to find the server physical location where the image will be saved. On line 13 we are then saving the image from the client to the server physical path using the SaveAs method. I am replacing the + sign with an _ since the + sign is not valid in a URL.

Then from line 15 to 17 I am saving the relative image path back to the database. So for example we might be saving /images/products/Image1.jpg back to our database.

On line 18 and on line 30 I am redirecting the user back to the Edit View and redisplaying the Edit Product MVC View. Note that I am passing the id parameter back to the controller. The Product should then be shown together with its new product image.

Finally let me give you part of the code to display an image on an ASP.NET MVC View. This code should be included in the ASP.NET MVC View which displays the product. I am not going to show you all the code which displays all the other Products fields, since this was covered in this blog. Rather I will only be showing the code which displays the image on our ASP.NET MVC View.

@if (!string.IsNullOrEmpty(Model.ProductImagePath))
 {
 <img src="@Model.ProductImagePath" alt="@Model.ProductDescription" title="@Model.ProductDescription" />
 }

In the above code there are some new things which I will explain. Note the IF statement using Razor syntax. Basically what I am doing is that if the Product has no image associated I am not displaying the img tag. Secondly, I am specifying the src of the Image as being the one which the ProductImagePath inside the Products table points to. Note that in these cases we append Razor code using the @ sign.

Run the application and you should end up with the an ASP.NET MVC View which resembles the one in Figure 2.

Figure 2 - Image uploaded and shown in ASP.NET MVC View

Figure 2 -Image uploaded and shown in ASP.NET MVC View

So I hope you found this blog post useful easy to follow. Till next time take care :) .

By

ASP.NET MVC 4 ViewBag and Dropdownlists

First of all I would like to welcome any first time visitors to my blog. Before I start this blog I would like to give a brief introduction to myself. My name is Mark Anthony Farrugia and, apart from being a Computing Teacher, I am a freelance web developer based in Malta,a small island in the Mediterranean. So now let me start this blog post :) .

The outcomes of this blog are to

  1. Discover what is the ViewBag and how this can be used to return data back to a View
  2. Use a DropdownList to display data for a foreign key column

The prerequisites to follow this blog are

  1. You should have SQL Server Express installed. You can install it from here
  2. You should have two tables Products and Categories inside your database
  3. You should have some understanding of LINQ To Entities

This blog will explain how you can give the opportunity to a user to select a Product Category from a dropdown list, for a specific Product. In the previous blog we saw how the user had to input the CategoryId manually. This, of course, is not the ideal situation since the user would have to remember all the ids for all the Product Categories manually.

So basically, the first thing we should be doing is to create a method which returns all Product Categories from our database. This method should be included in our business class which is included in our Models folder. This code is shown underneath.

/// <summary>
 /// Gets all product categories
 /// </summary>
 /// <returns>All product categories.</returns>
 public IQueryable<Category> GetCategories()
 {
 Models.MVCBlogDBEntities entities = new MVCBlogDBEntities();
 return entities.Categories;
 }

Once we are finished from our business method we need to call this method from our controller method. Basically, this information should be displayed in our ASP.NET MVC View, using a DropdownList. To display this information we need to make use of the SelectListItem which represents one single dropdown option made up of the Text and the Value. The Text property is the text which the user sees in the dropdown whilst the Value is the value stored for the option selected.

Let’s assume we wish to include our DropdownList inside the Create controller method, which basically serves as the controller which adds a new product.  The underneath code is the code snippet inside our controller method which basically creates a List of SelectListItems. For each SelectListItem we are setting its Value to the CategoryId, whilst we are setting its Text to the CategoryName. This would mean that we will be storing the CategoryId inside the ProductCategory foreign key whilst displaying the CategoryName.

[HttpGet]
public ActionResult Create()
{
 List<SelectListItem> Categories = (from p in
 new Models.DBProducts().GetCategories().ToList()
 select new SelectListItem()
 {
 Value = p.CategoryId.ToString(),
 Text = p.CategoryName
 }).ToList();
ViewBag.ProductCategory = Categories;
 return View();
 }

On line 11 I will then make use of the ViewBag which is a special object to pass the List of all SelectListItems back to the respective View. The ViewBag is no more than a container of objects which can then be accessed from the ASP.NET MVC View. You can place any object in the ViewBag and then access it using from the MVC View. We are naming the ViewBag variable ProductCategory so that it would have the same name as our ProductCategory field which can be found in the Products table. Recall that in our previous blog we ensured that the fields, found inside our ASP.NET MVC view, had the same names as the table’s fields found in our database. This will enable ASP.NET MVC to map the field values to their relevant database column fields.

Now let’s concentrate on how we will display the DropdownList in our ASP.NET MVC View. This can be done by using the DropDownList helper as shown in the underneath code. You should ensure that the name given is the same as the name given in the ViewBag found in our controller method.

@Html.DropDownList("ProductCategory")

If you run your ASP.NET MVC application and navigate to the Create Product controller method you should end up with a page like the one shown in Figure 1.

Figure 1 - Dropdownlist in View

Figure 1 – How the DropDownList will be shown in your ASP.NET MVC View

The actual HTML which is created is then shown underneath.

<select id="ProductCategory" name="ProductCategory"><option value="1">Motherboards</option>
<option value="2">CPU</option>
</select>

Note that each Category SelectListItem we have created in our Controller is represented by an HTML Option. We are storing the CategoryId as the Value whilst we are showing the CategoryName back to the user.

I hope that you found this blog interesting and that you have learned how to use DropdownLists in ASP.NET MVC.

By

Adding, Editing and Deleting data using ASP.NET MVC

First of all I would like to welcome any first time visitors to my blog. Before I start this blog I would like to give a brief introduction to myself. My name is Mark Anthony Farrugia and, apart from being a Computing Teacher, I am a freelance web developer based in Malta, a small island in the Mediterranean. So now let me start this blog post :) .

In the previous blog I have gone into the detail of how an ASP.NET MVC View can be used to display data. We also went into the details of how some of the ASP.NET MVC helper controls work and how they can be used.

At the end of this blog you should have an understanding of how to

  1. Create an MVC view to ADD a product
  2. Create an MVC view to EDIT a product
  3. Create an MVC view to DELETE a product

The prerequisites for this blog are

  1. Follow the previous blog where I explained how to create a View which lists all products and where for each products the user would have the possiblity to add/edit and delete products.
  2. Ensure you have a Products table inside an SQL Express table and that you have defined your LINQ To Entities model. You can follow this blog if you still haven’t done so.

So let’s start by creating the View which will add a new product. We will be creating two controller methods called Create which one will be decorated with an HttpGet used to display the View, while the other one will be decorated with an HttpPost which will be used to post the products information and adds the product to the database.

The HttpGet CreateNew method is shown underneath. You will note that this method only returns the respective View related to this controller.

[HttpGet]
public ActionResult Create()
        {
            return View();
        }

Now click the right mouse button inside the Create method and click on Add View. You should ensure that you create a strongly typed view of type Product. The ScaffoldTemplate should be Create since this View will be used to create a new product. This is also shown in Figure 1.

CreateNew Add View Template

Figure 1 – The CreateNew template which ASP.NET MVC makes available to create an ASP.NET MVC view which creates new records.

You will note that the new View which is created contains all the fields which a single Product entity has and this is shown underneath.

@model MVCForBlog.Models.Product
@{
    ViewBag.Title = "CreateNew";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>CreateNew</h2>
@using (Html.BeginForm())
 {
    @Html.ValidationSummary(true)
<fieldset><legend>Product</legend>
<div class="editor-label">
@Html.LabelFor(model => model.ProductName)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.ProductName)
 @Html.ValidationMessageFor(model => model.ProductName)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.ProductCategory)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.ProductCategory)
 @Html.ValidationMessageFor(model => model.ProductCategory)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.ProductDescription)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.ProductDescription)
 @Html.ValidationMessageFor(model => model.ProductDescription)
</div>
 <input type="submit" value="Create" />
</fieldset>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

Let me explain some new constructs which are included in this form. On the first line you have the following code @model MVCForBlog.Models.Product. This means that this View accepts a single Product instance.

On line 7 there is a tag which is Html.BeginForm. This is basically a construct which will then be rendered as a form tag which will post to the Create controller method which will then be used to add a new product and which we will be creating shortly. The HTML tag which is rendered when your MVC application runs is shown underneath

<form action="/products/Create" method="post">

On line 32 then there is an HTML submit button which will be used to submit the information on the form back to our Create controller method.

Before creating the Controller method which will be used to add a new Product we need to add the method in our business class which is located inside our Models folder. This method will actually add our product back to the database. This will be done using LINQ To Entities. This code is shown underneath and as you can see there is nothing complex which is being done. I am just actually adding a new Product instance back to the database.

/// <summary>
 /// Adds a new product back to the database.
 /// </summary>
 /// <param name="NewProduct">New product to be added.</param>
 public void AddProduct(Product NewProduct)
 {
 Models.MVCBlogDBEntities entities = new MVCBlogDBEntities();
 entities.Products.AddObject(NewProduct);
 entities.SaveChanges();
 }

Now let’s go back to our Create (HttpPost) controller method and let’s call this newly created method as shown in the underneath code.

[HttpPost]
 public ActionResult Create(Models.Product NewProduct)
 {
 Models.DBProducts dbproduct = new Models.DBProducts();
 dbproduct.AddProduct(NewProduct);
 return RedirectToAction("Index");
 }

Now let me explain how the above code works. As you will note the method Create accepts a Product instance parameter. This Product instance parameter will be filled from the Create View in our ASP.NET MVC project. Basically what MVC does is that it maps the Html fields to our Product entity model. So for example, if one of the Product’s field name is ProductName, and you have a textbox in your html with its Name set to ProductName, its value will be mapped to the Product’s ProductName field.

This way you can pass a whole object in the Controller method and be sure that all fields will be filled automatically. Recall that when we created the Create View we used some special ASP.NET MVC constructs such as  @Html.EditorFor(model => model.ProductName) which actually maps to our Product table.

So basically once the user clicks on Create button, in the Create view, the Product instance is passed back to our Create (HttpPost) controller method and the Product is added back to our database. The code at line 6 then basically redirects us to the Products Index controller method which actually lists all products.

Now that we have created the Controller method which creates a new product, let’s create the one which edits an existing product. Before we can create this controller, we have to create a method which returns one single Product according to a ProductId which is passed. This method should be created inside the Models folder inside our business class as shown underneath.

/// <summary>
 /// Gets one single product according to an id which is passed.
 /// </summary>
 /// <returns>One single product according to product id which is passed.</returns>
 public Product GetProduct(Guid ProductId)
 {
 Models.MVCBlogDBEntities entities = new MVCBlogDBEntities();
 return entities.Products.SingleOrDefault(p=>p.ProductId == ProductId);
 }

Now let’s create a Controller method called Edit as shown in the underneath code which calls the method which we have created. Note that whilst in the Create controller method we are not returning any object back to the view, in this case we are returning one single product back to the View. The View then displays this product.

[HttpGet]
 public ActionResult Edit()
 {</pre>
Models.DBProducts db = new Models.DBProducts();
return View(db.GetProduct(id));
}
<pre>

Let’s create a View which our ScaffoldTemplate is Edit as shown in Figure 2.

Edit Product View

Figure 2 – ASP.NET MVC View which edits an existing product.

The Edit View MVC code is shown underneath. As you will note the code resembles the Create ASP.NET MVC View. In fact we can say that it is practically the same view with the different that this View will be used to edit a specific product rather than adding a new product.

@model MVCForBlog.Models.Product
@{
    ViewBag.Title = "Edit";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Edit</h2>
@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)
    <fieldset>
        <legend>Product</legend>

        @Html.HiddenFor(model => model.ProductId)

        <div class="editor-label">
            @Html.LabelFor(model => model.ProductName)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.ProductName)
            @Html.ValidationMessageFor(model => model.ProductName)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.ProductCategory)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.ProductCategory)
            @Html.ValidationMessageFor(model => model.ProductCategory)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.ProductDescription)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.ProductDescription)
            @Html.ValidationMessageFor(model => model.ProductDescription)
        </div>

        <p>
            <input type="submit" value="Save" />
        </p>
    </fieldset>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

Test it out. Run your application, list all the products and click on Edit. You should get a window with the details of the Product you have clicked on. Our next step is to make our Edit work.

Before we create our Controller method which edits our product, we need to create the Edit method inside our business class which edits a Product instance. This code is shown underneath and this code might seem complicated for some of you. What I am doing is that I am getting the current Product from our database (line 8), attaching the existing product to our Entities instance (line 9) and then applying the new values on the existing Product (line 10). Finally I am saving the modified Product back to the database.

/// <summary>
 /// Edits a current product by getting the existing product and then applying the new values on the existing product.
 /// </summary>
 /// <param name="EditedProduct">Edited product.</param>
 public void EditProduct(Product EditedProduct)
 {
 Models.MVCBlogDBEntities entities = new MVCBlogDBEntities();
 Product ExistingProuct = entities.Products.SingleOrDefault(p => p.ProductId == EditedProduct.ProductId);
 entities.Products.Attach(ExistingProuct);
 entities.Products.ApplyCurrentValues(EditedProduct);
 entities.SaveChanges();
}

Let’s create the Edit controller which will act as our HttpPost method. This method will accept a Product instance and than call the Edit method inside our business class to edit the Product. Finally we redirect to our Product Index to list all the existing products. The product you have edited should now have the new values. This code is shown underneath.

[HttpPost]
 public ActionResult Edit(Models.Product EditedProduct)
 {
 Models.DBProducts dbproduct = new Models.DBProducts();
 dbproduct.EditProduct(EditedProduct);
 return RedirectToAction("Index");
}

So now what’s remaining is the Delete controller method which actually is the easiest one we will be having since we do not need to create a View for this. Let’s start by creating the method in our business class which actually deletes the product.

 /// <summary>
 /// Deletes an existing product.
 /// </summary>
 /// <param name="ProductId">Product id to be deleted.</param>
 public void DeleteProduct(Guid ProductId)
 {
 Models.MVCBlogDBEntities entities = new MVCBlogDBEntities();
Product ProductToDelete = this.GetProduct(ProductId);
 entities.Products.DeleteObject(ProductToDelete);
 entities.SaveChanges();
 }

In the above code I am first getting the existing product to be deleted (line 8) and then deleting the actual object from our database (line 9).

Now let’s create our Delete controller method which will accept an Id parameter which actually calls the newly created method. Basically this controller method is shown underneath. Make sure to call the parameter id because if not it will not work. In some future blog post I will also cover why this happens.

 public ActionResult Delete(Guid id)
 {
 Models.DBProducts dbproduct = new Models.DBProducts();
 dbproduct.DeleteProduct(id);
 return RedirectToAction("Index");
}

So that’s all for this blog. You should now have a View which actually lists all the products and then the user is able to Add/Edit and Deletes an existing product.
I hope you found this blog interesting and useful… CYA soon.

By

Create a simple ASP.NET MVC View to display data

First of all I would like to welcome any first time visitors to my blog. Before I start this blog I would like to give a brief introduction to myself. My name is Mark Anthony Farrugia and, apart from being a Computing Teacher, I am a freelance web developer based in Malta which is a small island in the Mediterranean. So now let me start this blog post :) .

In this blog I will give an introduction on how to display data in an ASP.NET page. In particular I will be displaying products information in an ASP.NET MVC view. This information will be returned from an SQL Express database using LINQ To Entities. I will be explaining LINQ To Entities in a future blog but since what I will be covering is very easy I am sure you will not find any problems to follow this tutorial.

The outcome for this blog is thus

  1. To list records back from a database
The prerequisites to follow this blog are
  1. Installed SQL Server Express database. You can install it from here.
  2. Have a Products table as will be shown soon
  3. Know how to create a LINQ To Entities model which will help us in retrieving and updating records
 The Products table which we will be using in this blog should have these fields defined
  1. ProductId (uniqueidentifier)
  2. ProductName (varchar(50))
  3. ProductDesciption (varchar(50))
  4. ProductCategory (smallint)

Please note that ProductCategory will be related to another table Categories but for now I will not take this relationship into consideration

In the ASP.NET MVC Models folder (Figure 1) I will include the LINQ To Entities model. This LINQ To Entities model has only one single entity which is the Product entity which maps to the Products table. I will also place the classes which interact with the LINQ To Entities model which modify and retrieve data inside this folder. You will thus note that in this folder I will place anything which relates to the business layer.

Figure 1 - LINQ To Entities

Figure 1 – LINQ To Entities

Please note that normally I do not place the LINQ To Entities model and business logic inside the Models folder. Rather I normally create separate class libraries which provide the business logic. However, for now, I will be including everything in a single project.

The LINQ To Entities code which returns our all our products is shown underneath.

public IQueryable Product GetProducts()
{
Models.MVCBlogDBEntities entities = new MVCBlogDBEntities();
return entities.Products;
}

This code is basically some simple LINQ To Entities code which returns all our existing products.

Our first step is to create our Products controller which will be responsible in calling anything related to the Products (modifying and retrieving data) and then displaying it back to our views. If you are still unsure how to create controllers and views please refer to this blog post.

Add a new controller called ProductsController shown in Figure 2. Thus the user will be able to access our controller methods using our website url /Products. Our Index method will be responsible to get all the available products and return it back to the view.

Figure 2 - Products Controller

Figure 2 – Products Controller

Go into the Index method of our Products controller, click the right mouse button and click on Add View.

Now this is the fun part :) . Remember that our Index controller method will return a list of products from the LINQ To Entities model. Select Create a Strongly Typed View and select the Product class which is our LINQ To Entities model class. In the ScaffoldTemplate select List, as shown in Figure 3. Click on OK and your first ASP.NET MVC view which lists data is ready.

Figure 4 - Add View and Scaffold

Figure 3 – Add View and Scaffold

Now go back to your Index controller. To pass the Products list back to your view you need to modify your Index controller as shown below.

public ActionResult Index()
{
 Models.DBProducts db = new Models.DBProducts();
 return View(db.GetProducts());
}

Basically in the above code we are calling GetProducts which basically returns all our products.

If you now return your application and type /Products/Index in your URL you will view all your products as shown in Figure 5.

Products List

Figure 5 – Products List

 Can you see how easy it is to display data in a view from a controller? I’m sure that from now on you will be using this to display data :) .

In my next blog post I will going into detail on the HTML markup which is generated in the View we have created in this blog post.

By

Creating our first ASP.NET MVC View

In this blog post I will be creating our first simple ASP.NET MVC View which will just display a Hello World message :) . At the end of this blog you should be able to

  1. Start understanding how ASP.NET URL rewriting works
  2. Understand how to pass messages between a Controller and a View
  3. Understand how Controllers should be named
  4. Understand the mapping between Controller and their respective Views
  5. Understand where Views should be stored

To create our first View we will first be creating a Controller method inside the HomeController. Before I create our first View it is good to understand how ASP.NET controllers link to Views by giving several examples.

The first thing to understand is that all Controller names need to end with the Controller name. For example in the sample MVC application there are 2 controllers which are the HomeController and AccountController, as shown in Figure 1. In these controllers there are several methods which link to ASP.NET MVC Views. For example, in the HomeController there are 3 controller methods which are Index, About and Contact as shown in Figure 2.

Figure 1 - Home and Account Controller

Figure 1 – Home and Account Controller

Figure 2 - HomeController Methods

Figure 2 – HomeController Methods

How are these Controller methods called? I will be giving several examples underneath of different URLs the user can type in order to call these Controller methods

  1. http://localhost/Home/Index – The Index Controller method inside the HomeController is called.
  2. http://localhost/Home – The Index Controller method inside the HomeController is called
  3. http://localhost/Home/About -  The About Controller method inside the HomeController is called.
  4. http://localhost/Home/Contact -  The Contact Controller method inside the HomeController is called.

First of all if you take a look at the above URLs you will immediately realize that the URLs to access ASP.NET MVC pages are totally different from calling ASP.NET pages. The above URLs are much better for Search Engine Optimization (SEO), and sometimes these type of URLs are called slugs.

Taking the example URL shown underneath you will note that the first part is the Controller name while the second part is the Controller method name. So in the example shown Home represents the Controller name (in fact there is a Controller named HomeController), while Index is the Controller method name (in fact there is a method called Index in the Home Controller. (Figure 3) (Figure 4)

Figure 3 - Naming structure inside controllers

Figure 3 – Naming structure inside controllers

Figure 5 - URL Structure

Figure 5 – URL Structure

Let’s now create our ASP.NET MVC 4 view. Create a controller method called Test inside the HomeController, as shown in Figure 5 and type the following code return View(); This code basically returns the matching View with this Controller

Figure 5 - Test method

Figure 5 – Test method

Let’s run our application and let’s try to access our Controller method by typing http://localhost/Home/Test. You will see that an exception as shown in Figure 6 will be returned. The reason for this exception is that ASP.NET MVC will try to search for the relevant ASP.NET MVC view which relates to the Controller method. This View which should be named Test.cshtml should be stored inside the VIEWS-HOME folder. If this is not found then ASP.NET MVC will show the exception shown in Figure 6. ASP.NET MVC will try to find this page in several other locations and after failing to find any matching pages an exception will be thrown.

Figure 6 - Exception when View not found

Figure 6 – Exception when View not found

So where should ASP.NET views should be stored? All ASP.NET MVC views are stored inside the VIEWS folder. The naming structure which ASP.NET MVC adopts is that the folder relates to the Controller name, while the page will be named according to the method name.

So taking into account the example shown in Figure 5, a page named Test.cshtml should be created inside the Home folder. In fact, as shown in Figure 7, you will note that there are 3 pages which are related to the 3 methods which have been automatically created by our sample application. These views are named Home.cshtml, About.cshtml and Contact.cshtml.

Figure 7 - Sample Views

Figure 7 – Sample Views

Let’s go back to our example. If we wish to create a new View which will serve as our Test page we should go inside the Test controller method, click the right mouse button and then click on ADD VIEW. Figure 8 shows how this should be done.

Figure 8 - Add View

Figure 8 – Add View

You will then have to select several options. For now we will not go into detail into what this page provides. You only have to make sure that you select the MasterPage which in our sample application is called _Layout.cshtml and is found under the Shared folder, as shown in Figure 9. A page will be created. Now if you type in the URL http://localhost/Home/Test you will see that the page correctly opens as shown in Figure 10.

Figure 9 - Add View options

Figure 9 – Add View options

Figure 10 - View correctly loads

Figure 10 – View correctly loads

Now let’s try to send a message back to our view. To do this we can use what so called the ViewBag which is used as a temporary storage which can then be passed and used by our ASP.NET MVC View.  The code shown in Figure 11 creates a ViewBag variable called Message and stores a Hello World message in this ViewBag variable. You can then display this message inside the View by using Razor syntax as shown in Figure 12. Note that when typing Razor code inside the View you need to preappend it with the @ sign.

Figure 11 - ViewBag

Figure 11 – ViewBag

Figure 12 - Razor inside View

Figure 12 – Razor inside View

Now run the application, type in http://localhost/Home/Test, and you see that the Hello World message is correctly displayed, as shown in Figure 13.

Figure 13 - View with message

Figure 13 – View with message

So enough for this blog…. I hope you found it useful.

By

Creating our first MVC 4 application

First of all I would like to welcome any first time visitors to my blog. Before I start this blog I would like to give a brief introduction to myself. My name is Mark Anthony Farrugia and, apart from being a Computing Teacher, I am a freelance web developer based in Malta which is a small island in the Mediterranean. So now let me start this blog post :) .

In this blog post I will focus on the creation of our first ASP.NET MVC application using Visual Studio. If you are familiar with ASP.NET you will soon realize that an ASP.NET MVC project folder structure is totally different from an ASP.NET application.

To start off you need to create a new ASP.NET MVC project type using Visual Studio, as shown in the underneath screenshot. In my case I will be creating an ASP.NET MVC 4 application. If you do not have this project template you can download it from here.

Basically you can now decide to either create an EMPTY ASP.NET MVC application or an ASP.NET MVC template project which will include some sample classes to help you get familiar with ASP.NET MVC. Frankly, especially if you’re still a beginner in ASP.NET MVC, it’s best to select the sample ASP.NET MVC application so you can have some initial understanding on how ASP.NET MVC works.

Creating our first ASP.NET MVC application

Creating our first ASP.NET MVC application

In the next step as shown underneath you will need to select which VIEW ENGINE you wish to use. You can either choose ASPX or RAZOR. Basically these VIEW ENGINE types relate to how you would write inline code inside VIEWS. For someone who is familiar with ASP.NET the ASPX engine might look much more familiar than Razor. However the code inside VIEWS using the Razor engine is much more readable than code written in ASPX. In this, and future blogs, I will be using the Razor syntax to create my own own VIEWS. I will be covering the fundamentals of Razor. So do not worry because even if you do not know anything about Razor you would still be able to understand what I will be doing.

Selecting between RAZOR or ASPX

Selecting between RAZOR or ASPX

Different folders will be created once you create an ASP.NET MVC application, as shown underneath. The most important folders which you definietly need to understand are the following

  1. Controllers – in this folder you will find all the available controllers which will be used to pass data from the model to the view
  2. Model – in this folder you will find all the available models which will be used by the controllers back to the views. In this folder you will find C# classes which might include business methods, or other classes which will be used by controllers.
  3. Views – in this folder you will have all the available Views which are the actual pages which your users will be viewing. When creating a project with Razor syntax the extension of these views will be .CSHTML whilst if you select the ASPX view engine the extension would be .ASPX.
  4. Content – This is where items such as stylesheets are stored.
  5. Scripts - This is where Javascript files are stored. You will note that Visual Studio automatically adds JQuery files to this folder since the sample application makes use of JQuery to implement validation.
  6. Images – This is where specific images used by your website can be stored.
  7. App_Start – This is a new folder introduced in ASP.NET MVC 4 and include some classes which are responsible for some initial configuration of your website.
ASP.NET MVC Folder Structure

ASP.NET MVC Folder Structure

You can now run your first MVC application. You will note that the sample application which Visual Studio provides contains all the familiar elements of all the popular websites such as Registration, Login, Forgot Password etc. We will be creating some new pages and modify this sample website to start learning how MVC works. Underneath a screenshot of your the sample application should look like.

ASP.NET MVC 4 Sample Application

ASP.NET MVC 4 Sample Application

By

Introduction to ASP.NET MVC

Introduction to ASP.NET MVC

First of all I would like to welcome any first time visitors to my blog. Before I start this blog I would like to give a brief introduction to myself. My name is Mark Anthony Farrugia and, apart from being a Computing Teacher, I am a freelance web developer based in Malta which is a small island in the Mediterranean. So now let me start this blog post :) .

In this blog I will cover ASP.NET MVC, which, in my opinion, is one of the best things that Microsoft have ever developed.

So let me start with some basic history on ASP.NET. The first ASP.NET version was out in 2001 and it was a complete revamp on the previous ASP version. At those days what Microsoft tried to do was to try and make web development as easy as developing desktop applications. They provided UI elements such as the gridview, repeater, drop down lists, list boxes etc which resembled other familiar controls which existed in desktop applications. One should remember that at those times desktop applications were by far the most common types of applications when developing enterprise applications. Microsoft felt that the tide was soon going to turn, and they felt that developers were soon going to choose web applications when developing their own enterprise applications. In fact they were right, because enteprrise web applications became very popular with the advent of server side web technologies such as ASP.NET and PHP.

I used to love programming in ASP.NET… but guess what…. now I feel that it does not suit me anymore with the advent of one of the best Microsoft technologies which is ASP.NET MVC. The main drawbacks of ASP.NET is the way how it renders its controls and the compatibility with different browsers. You end up having a gridview showing properly in Internet Explorer but not in other browsers such as Chrome or Firefox. Other problems I used to encounter was its difficulty in linking it with client side technologies such as Javascript and mainly JQuery. I also used to have big problems trying to integrate AJAX calls in my application, having to include controls such as the ScriptManager etc. Anyway no more on ASP.NET :)

I have been developing ASP.NET MVC applications for the past 3 years and I started with ASP.NET MVC 2. The current ASP.NET MVC version is 4 and you can find it here. ASP.NET MVC is an open source project and this is also a good move in the right direction. All the previous ASP.NET versions were a closed box, and I still remember having big problems when Microsoft used to publish a new version because of compatibility issues. ASP.NET MVC integrates tightly with client side libraries such as JQuery and in fact JQuery libraries are created the moment you create an ASP.NET MVC application in Visual Studio. For those of you who do not know anything about JQuery I will also cover this in further post in my blog.

So let’s start getting our hands dirty on ASP.NET MVC. Basically MVC stands for Model, View, Controller and its a completely different methodology on how web applications are developed. It’s important to note that MVC is not a Microsoft technology but rather it is a common design pattern or methodology which also exist in other languages such as PHP and Java. In the past years this methodology has become increasingly popular with web technologies. If you are extremly familiar with ASP.NET you might find ASP.NET MVC a little bit difficult at first. However, once you get the grasp of it I’m sure you will never look back.

MVC seperates the Presentation Layer, Business Layer and Application Layer in three different layers.

The Model can be considered as the place where the Business Layer is placed and one might find things such as database methods, LINQ TO Entities classes etc.

The Controller can be considered as the application layer and is the layer responsible for interacting with the Model and presenting data to the VIEW.

The View is then our familiar ASP.NET page and is the one responsible for presenting data to the user.

So enough theory…. In my next blog post I will guid you to create your first MVC .NET web application.