Tip #1: ASP.Net MVC Shortcuts

September 1, 2009 Leave a comment

Here are some nice shortcuts that are for ASP.Net MVC Application that will help you develop your web applications at a faster pace.

First to add a view, simply hold down (Ctrl M, Ctrl V)

 

add_view

 

and Adding a Controller to your new MVC App is easy as well just by holding the following down (Ctrl M, Ctrl C)

add_controller

 

Well hope this all helps. 

 

Happy Coding!

Understanding Models using the ASP.Net MVC Framework

August 28, 2009 Leave a comment

If you don’t know about ASP.Net MVC Framework I admonish you to do your research.  It’s a Framework / design pattern to make astonishing web applications with ease, for it separates the Models, Controls, and Views from each other so you can quickly update or modify any piece of your web application without changing much code.  I’m not going to speak much on the MVC Framework, for I’ll expect you to have some knowledge on it.  I’ will be focusing on using the Model part of the MVC Framework, and using the Entity Framework to doing any type of work on a database, and having it view in your web application.

An ASP.Net Model contains all the business, validation, and data access logic required by your application.  In other words a Model contains all of your application except your view logic and controller logic.  When you build an ASP.Net MVC application the majority of your time will be building the Model.  I will show you how to create model classes by using the Microsoft Entity Framework.  Alright, so let’s get started.

First Creating the Database and tables

First we will create a database called ProductsDB.  We will then create a table and call it Products.  The table definition should look as the following image below.

ProductDBTable

Make sure that your id tag is the primary key, and it’s the primary key and the identity for that database.

Next i filled in some values with a some data I got from the www.dell.com website.  Yes, we’re practically building a smaller application of Dell computers.  I only filled in the first 3 computers from the XPS730 Dell section, but still the only difference between a website like Dell and having 75,000+ records, or just 3 records like I have is taking the time to making the size of the database the business and data access layer logic is all the same.

dataModelList

Since this is a medium size table not all fields can be shown, and I have the first 2 Product Name, which all are XPS 730x, and the id which you can leave null and have Visual Studios auto generate one for each entity in the database.  If the text looks a little blur and you can’t read them all you can either download the code below, or go to the Dell website and look for the XPS series and literally copy and paste each field as I did.

Now since we want to access this from our ASP.Net MVC application we must use the Microsoft Entity Framework to generate a data model.

Steps in Creating the data model.

  1. Right Click on the model folder click on Add New Item
  2. When the Add New Item dialog click on ADO.Net Entity Model

In the wizard go through and choose the database we created.  In the Choose your database object step choose the Products table and enter the namespace Models.  Click finish and we’re ready to start programming!

After you have created the Products data model change the name from Products to Product making it singular since it’s technically referring to a single product.

Creating the Application

Open up the HomeController that comes default to your Application.  Now we’re ready to start coding.

First we need reference our model, so first let’s add that by adding the following code below,

using ProductExample.Models

Next, we want to add a initiate the Entity Framework object of the ProductDB, which we created, so add the following code after the class initiation.

private ProductDBEntities _entities = new ProductDBEntities();

Finally we have our ActionResult functions. Which is like the glue to the Views that will be auto generated in Visual Studios once we get done with the coding in the controller.

First the index,

public ActionResult Index()
{
return View(_entities.ProductSet.ToList());
}

This casting the entire _entities object database into a single list and sends it to the View.

Next righclick on Index() and select Add View. Choose a strong type view, and make sure in the data model selection you select the Product.Model, and in the type of view list you choose list. This auto generates our view code for our database in a structured list table passing the _entities ProductSet as a list to the View state. Now we’re completely done with the Index.

Next, I will do the details, edit, and create at the same time, since it’s much the same as the Index code,

public ActionResult Details(int id)
{
var result =(from p in _entities.ProductSet
               where p.id == id
              select p).FirstOrDefault();
return View(result);
}

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

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create([Bind(Exclude="id")] Product productToCreate)
{
try
{
_entities.AddToProductSet(productToCreate);
_entities.SaveChanges();
return RedirectToAction("Index");
}
catch
{
return View();
}
}

public ActionResult Edit(int id)
{
var productToEdit = (from p in _entities.ProductSet
where p.id == id
select p).FirstOrDefault();

return View(productToEdit);
}

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(Product productToEdit)
{
try
{
var originalProduct = (from p in _entities.ProductSet
where p.id == productToEdit.id
select p).FirstOrDefault();

_entities.ApplyPropertyChanges(originalProduct.EntityKey.EntitySetName, productToEdit);
_entities.SaveChanges();
return RedirectToAction("Index");
}
catch
{
return View();
}
}

With each of the Function right click on them select the same database model, but in the view type choose the correct type of either edit, details, or create and there you’ll auto create all view types of edit, details, and create with no code in the view section.

Next is the delete code, which is the same, but instead of auto generating a view in the view type dialog when we add a view we create the code ourselves. The following code adds the delete functionality to our MVC Application.

public ActionResult Delete(int id)
{
var productToDelete = (from p in _entities.ProductSet
where p.id == id
select p).FirstOrDefault();</code>

return View(productToDelete);
}

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Delete(Product productToDelete)
{
try
{
var originalProduct = (from p in _entities.ProductSet
where p.id == productToDelete.id
select p).FirstOrDefault();

_entities.DeleteObject(originalProduct);
_entities.SaveChanges();
return RedirectToAction("Index");
}
catch
{
return View();
}
}

Now we must create our Delete.aspx view. Right click on your View/Home folder and add create new web form. Name it Delete.aspx. Put the following code below in the file and save it.

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<ProductExample.Models.Product>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
	Delete
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

    <h2>Delete</h2>
    
    <% using (Html.BeginForm()) {%>
            <p>
            Are you sure you want to delete <%= Html.Encode(Model.Product_Name) %>?
            
            </p>
            <p>
                <input type="submit" value="Delete" />
            </p>

    <% } %>
    
</asp:Content>

Lastly we must add the Html.ActionLink of the Delete to the Index, since we created the delete functionality without auto generating any of the code. Not that it was difficult it just wasn’t supported.

So finally in the Index.asp View add the following code where you see the Html.ActionLinks forEdit and Details.

<%= Html.ActionLink("Delete", "Delete", new { id = item.id })%>

Now we’re done and can test out the project.

Project Files
Product Example

You should get the following results, which can CRUD the database of the dell products on a fly.

Follow

Get every new post delivered to your Inbox.