Sunday, July 31, 2011

JqGrid in ASP.NET MVC3 Code First Project

JqGrid is one of the most popular and flexible Jquery based component which is available for ASP.NET and PHP. These components are for sale included in a bundle of other useful Jquery plugins such as JqChart, JqTreeGrid and many more. If you can afford, then you can buy the plug-in already integrated to ASP.NET MVC 2+. But for those who are interested to learn, Pinoy Brown Bag Sessions will show you how its done in a simple way. 
Using JqGrid in Asp.NET MVC 3 with VB.NET


I'v been using JqGrid plugin during my college years. The plug-in was still in its earlier version and is available opensource for PHP developers only. Back then, using JqGrid in ASP.NET was still an issue in forums and other blogs. a documentation of JqGrid for PHP is available in this website which I have used for 3 years by now and still it does work for me. 

For this brown bag session download the opensource demo package here. You can also download from github here. All you need to do is run the demo in your local server and try some of the examples provided for you. NOTE that the demo you downloaded is for PHP. Based on that demo we can arrive with a JqGrid in our ASP.NET MVC 3 project with VB.NET. 

To start lets create the view for the JqGrid. In our previews post I have already included the <div> with the id "jqgrid_product" for the grid view. The code is shown below. 

<div id="toystoregrid">
<table id="jqgrid_product" class="scroll" cellpadding="0" cellspacing="0" style="cursor: pointer;
-moz-user-select: none;">
</table>
<div id="jqpager_product" class="scroll" style="text-align: center;">
</div>
<input id="setcols" type="button" value="Set Columns" />
</div>

Next we then add the javascript for this plug-in to identify its properties such as column name, column format, caption and more. To do this lets insert a Jquery AJAX function just before the last closing div tag of our view in index.vbhtml file.

<script type="text/javascript">
$.getScript("@Url.Content("~/jsx/Home.js")");
</script>

This function loads a javascript file named Home.js in our directory. The purpose of this function was just actually to separate the javascript from the view or HTML in order to give you a clearer view on how its done. Next in our Home.js file lets add some Jquery and the JqGrid plug-in as well. Here is the code snippet for shown below.

Home.js

$(function () {
$("#jqgrid_product").jqGrid({
scrollrows: true,
url: "Home/jsontry",
datatype: "json",
colNames: ['ID', 'Name', 'Description', 'Price'],
colModel: [
{ name: 'Tbl_Id', index: 'Tbl_Id', width: 150, resizable: false, sortable: false },
{ name: 'Tbl_Name', index: 'Tbl_Name', width: 250, resizable: false, sortable: false },
{ name: 'Tbl_Description', index: 'Tbl_Description', width: 250, resizable: false, sortable: false },
{ name: 'Tbl_Price', index: 'Tbl_Price', width: 150, resizable: false, sortable: false }
],
mtype: "POST",
imgpath: 'themes/basic/images',
pager: $('#jqpager_product'),
rowNum: '10',
rowList: [10, 20, 30],
rownumbers: true,
viewrecords: true,
caption: "Sample JQgrid",
height: '200',
width: '1024',
autowidth: true
});
});

You can see from above the code snippet for our JqGrid. Notice that the JqGrid function is in-closed with a Jquery which is equivalent to a document.ready() function in javascript. If you downloaded the demo of JqGrid, the script shown above is the Loading Data demonstration on JSON. JavaScript Object Notation (JSON) is a lightweight data-interchange format. It is easy for humans to read and write. I prefer JSON than XML in terms of speed and readability. Also that ASP.NET MVC 3 supports JSON. I will show you that not long from the code behind. 

Let me discuss some important lines with you as we go along. We have this line $("#jqgrid_product").jqGrid({, the id of the table we created earlier in our view. This identifies the target element of the plug-in. In order to connect to our database we have the URL given in this line url: "Home/jsontry",. The URL identifies "Home" which is the controller and "jsontry" which is that method that we will create later. colNames: and colModel: are the properties that identify our column and the model. You can read more about this properties in the documentation available in PDF format here. You can try to experiment with the other properties and see how it affects your grid. 

We are now ready to do the code behind. But first lets create a simple class that would contain the data that we return to our grid as JSON. The code blow shows the jqgriddata.vb class. 

jqgriddata.vb  

Public Class Jqgriddata
Private _id As Object
Private _cell As Object

Public ReadOnly Property id As Object
Get
Return _id
End Get
End Property

Public ReadOnly Property cell As Object
Get
Return _cell
End Get
End Property

Public Sub New(ByVal idpass As Object, ByVal cellpass As Object)
_id = idpass
_cell = cellpass
End Sub
End Class

I will discuss the two properties of the class later in this brown bag as we finish the code for the controller.

Now lets do code behind for our HomeController.vb. For those who have downloaded or created the project the code below will replace the code from your controller as we do the jquery method. For the first method we have this code below. 

Function Index() As ActionResult
Return View()
End Function

Function jsontry(ByVal data As FormCollection) As ActionResult
Dim page = data("page") 'the current page for paging
Dim limit = data("rows") 'number of rows per page
Dim sidx = data("sidx") 'pass the row value used for sorting
Dim sord = data("sord") 'sort order (asc or desc)
Dim countrows As Integer
Dim totalpages As Integer

If sidx.ToString <> "" Then
sidx = 1
End If
countrows = (From p In _entities.Products _
Select p).Count() 'linq query to count for number of rows
If countrows > 0 Then
totalpages = Math.Ceiling(countrows / limit)
Else
totalpages = 1
End If

If page > totalpages Then
page = totalpages
End If

Dim start As Integer
start = limit * page - limit

Dim result = (From p In _entities.Products _
Select p) 'the query to fetch the row values from the database

Dim cell = result.ToArray()
Dim celly = result.ToList()
Dim response As New Dictionary(Of Object, Object)
Dim rows As New ArrayList

response.Add("page", page)
response.Add("total", totalpages)
response.Add("records", countrows)

Dim i = 0
Dim x = 0
'some loop in order to extract the data from our entity to an arraylist
For Each row In cell
Dim cellx As New ArrayList
For Each c As System.Reflection.PropertyInfo In row.GetType().GetProperties()
cellx.Insert(i, row.GetType().GetProperty(c.Name).GetValue(row, Nothing))
i = i + 1
Next
rows.Insert(x, New Jqgriddata(row.Id, cellx)) 'the data is added to a Dictionary basically an array
i = 0
x = x + 1
Next
response.Add("rows", rows)
Return Json(response) 'return the response as JSON.
End Function

Wow! Quite a long VB script you have their. I added some comments though to discuss how the code behind produced the return value of the method. I only applied the PHP script and manage to somehow convert it to VB.NET. My first project doing this was with C# which was the easier version I guess. Yet here's a VB example for you VB users. With this code I am sure you can easily do it with C#.

And we are done with the the brown bag session. Try to run the code and with that your grid must appear smoothly in you index page. We just have made our JqGrid in ASP.NET MVC 3. I used firebug to display the post data from the grid as well as the response from the code behind. 

Sample JqGrid in ASP.NET MVC 3 with VB.NET.
I added some JqueryUI themes that you can download from their website. This is a Dot Luv theme from long ago. They have a lot more options to choose from with their latest version of JqueryUI nowadays. I also added a property from JqGrid which enables you to set the columns to display. Try to read and explore the documentation for this function. Here I have the image below.

JqGrid Set Columns function example.
You can view some result and also help you with debugging by using some tools like FireBug. If you are using  FireFox web browser the plug in is available from the website. Here are some results from my FireBug. 

JqGrid post data for the MVC controller method.

Some JSON results from ASP.NET MVC 3.
Other interesting results from FireBug.
That was all for now. I hope you have learned some few things from our short brown bag sessions. The next post will be on the CRUD. I will demonstrate how I used Jqury Populate and Validation in my ASP.NET MVC 3 application. Stay tune for more of Pinoy Brown Bag Sessions tutorials. Please feel free to as questions and feedback to improve the project. Thank you!

JqGrid in ASP.NET MVC3 Code First Project

JqGrid is one of the most popular and flexible Jquery based component which is available for ASP.NET and PHP. These components are for sale included in a bundle of other useful Jquery plugins such as JqChart, JqTreeGrid and many more. If you can afford, then you can buy the plug-in already integrated to ASP.NET MVC 2+. But for those who are interested to learn, Pinoy Brown Bag Sessions will show you how its done in a simple way. 
Using JqGrid in Asp.NET MVC 3 with VB.NET


Wednesday, July 27, 2011

Start Google Plus | Convert Facebook to Google+

Start Google Plus | Convert Facebook to Google+

I woke up this morning and got this thing from a someone in Google Plus. I'v been using and application called Digsby for the last few months for me to post a status or a short blog to Facebook and Twitter. Just this month I'v been added by a friend on Google plus and started to create circles of friends, family, acquaintance and more. Now I'm having hard time to post some status to three different social networks. Good thing some generous people came up with a browser plugin for Chrome and Fire Fox. So get more out of your social life. 


Some post I made earlier from G+ to FB and Twitter.
Some personal message for testing the plugin in Chrome.



Start Google Plus | Convert Facebook to Google+

Start Google Plus | Convert Facebook to Google+

I woke up this morning and got this thing from a someone in Google Plus. I'v been using and application called Digsby for the last few months for me to post a status or a short blog to Facebook and Twitter. Just this month I'v been added by a friend on Google plus and started to create circles of friends, family, acquaintance and more. Now I'm having hard time to post some status to three different social networks. Good thing some generous people came up with a browser plugin for Chrome and Fire Fox. So get more out of your social life. 

Download ASP.NET MVC3 Code First Project

Last week their have been email coming from readers asking for the source code of the ASP.NET MVC 3 Entity Framework Code First implementation. GOOD NEWS! I have finally uploaded the sample project on my github public repo. The ToyStoreMVC3 is written in VB.NET and you can now download or fork the solution in your own github account. For those of you who already have a github account, you may keep track of the projects that I am into by following me on github. 

I will be entertaining feedback on the project through email and through comments. Feel free to discuss bugs and other modifications to enhance the project. Thank you for supporting my blog and watch out for more.

Download ASP.NET MVC3 Code First Project

Last week their have been email coming from readers asking for the source code of the ASP.NET MVC 3 Entity Framework Code First implementation. GOOD NEWS! I have finally uploaded the sample project on my github public repo. The ToyStoreMVC3 is written in VB.NET and you can now download or fork the solution in your own github account. For those of you who already have a github account, you may keep track of the projects that I am into by following me on github. 

I will be entertaining feedback on the project through email and through comments. Feel free to discuss bugs and other modifications to enhance the project. Thank you for supporting my blog and watch out for more.

Tuesday, July 26, 2011

Jquery AJAX with ASP.NET MVC3

The next series of brown bag sessions is about using Jquery AJAX with ASP.NET MVC 3. This project is the continuation of ASP.NET MVC 3 and Entity Framework Code First project. The methods I used in this project are undocumented. Feel free to apply or modify these tips and tricks to your own project. As we go along with the topic I will include the references of the plug-ins used for you to study and download the source. It is recommended that you enhance the methods and the code structure for production purposes. Greate! Let the learning begin!

Using Jquery AJAX with ASP.NET MVC 3



Figure 1. ASP.NET MVC 3 Script folder
My journey with Jquery started two years ago back in my college days. Jquery is a fast, concise, library that simplifies how to traverse HTML documents, handle events, perform animations, and add AJAX. Sounds good! No wonder why ASP.NET MVC comes with Jquery as well. Figure 1 shows the Script folder of the MVC project. The once that are highlighted are the javascript files from the ASP.NET MVC framework while the others are just added for the purpose of this demonstration. you can see the Jquery library and other jquery plug-ins that are available for this framework and that these js files are already integrated to your created project. So far, for this version of the MVC framework the latest virsion of Jquery is 1.4.1. As you can see I have added a newer version of Jquery in this project which is 1.4.2. You can checkout the Jquery website for more updates with the library which as of this date is in version 1.6.2. Their might be some compatibility issues with the MVC 3 framework and for that please refer to the documentation provided at their website.

Let us begin the demonstration by making a backup copy or our previews project. If you have read my previews post on the ToyStoreMVC3 project then you can modify that one for this project. But I suggest to backup the old one just in case you need a reference on the view scaffolding method.

Navigate to Views >Shared and open _Layout.vbhtml. This is the main page which contains the head and the body of your HTML. It is used as the master page which will load the views dynamically in its content. Lets include the necessary js and css files needed for the project.

<head>
<title>@ViewData("Title")</title>
<link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
<link href="@Url.Content("~/Content/ui.jqgrid.css")" rel="stylesheet" type="text/css" />
<link href="@Url.Content("~/Content/Jqueryui/jquery-ui-1.7.1.custom.css")" rel="stylesheet" type="text/css" />
<link href="@Url.Content("~/Content/ui.multiselect.css")" rel="stylesheet" type="text/css" />

<script src="@Url.Content("~/Scripts/jquery-1.4.2.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery-ui.js")" type="text/javascript"></script>
@*JSON*@
<script src="@Url.Content("~/Scripts/jquery.json-2.2.min.js")" type="text/javascript"></script>
@*Jquery Validation*@
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
@*Jquery Populate*@
<script src="@Url.Content("~/Scripts/jquery.populate.min.js")" type="text/javascript"></script>
@*JqGrid*@
<script src="@Url.Content("~/Scripts/Jqgrid/i18n/grid.locale-en.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/Jqgrid/jquery.jqGrid2.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/Jqgrid/ui.multiselect.js")" type="text/javascript"></script>
</head>

This is the head tag and the scripts I used. Notice the src and href properties of the script and link tags. The method use Razor to give the URL value of the file. Also I included some Jquery plug-ins that will be used in this demo. We have Json, Jquery Validation, Jquery Populate, and JqGrid. I'll tackle each of the plug-ins as we go along.

View - Jquery Style

In the previews brown bag session, we learn about scaffolding views with ASP.NET MVC 3 framework. This time I will show you how to use Jquery with the view to manipulate the containers and do some animation just for fun. To start with lets delete the views we have created using the scaffold method. Navigate to Views > Home folder and remove the following files shown in Figure 2.

Figure 2.  Create, Delete, Details and Edit views.
Now you are suppose to be left with these files in the Views folder as shown in Figure 3.

Figure 3.  Views folder for Jquery project.
Index.vbhtml

In this project I will be using the Index.vbhtml file as a view. This view will carry out the CRUD (Create, Read, Update, Delete) function with the help of Jquery AJAX. As I have said a while ago, the method used is undocumented. I'd be open for discussions and corrections who might have some interesting ideas regarding this topic. Ok! here is the code for my view.

@Modeltype ToyStoreMVC3.Product
@Code
ViewData("Title") = "Home Page"
Layout = "~/Views/Shared/_Layout.vbhtml"
End Code
<h2>
Home</h2>
<input id="butCreate" type="button" value="Create" />
<input id="butEdit" type="button" value="Edit" />
<input id="butDelete" type="button" value="Delete" />
<div id='ajaxpage'>
<div id="toystoregrid">
<table id="jqgrid_product" class="scroll" cellpadding="0" cellspacing="0" style="cursor: pointer;
-moz-user-select: none;">
</table>
<div id="jqpager_product" class="scroll" style="text-align: center;">
</div>
<input id="setcols" type="button" value="Set Columns" />
</div>
<div id="toystorediv" style="display: none">
<form id="toystoreform">
<fieldset>
<div id="preloader" style="display: none">
<img src="../../Image/loader2.gif" /></div>
<input id="Id" name="Id" type="hidden" value="" />
<div class="editor-label">
@Html.LabelFor(Function(model) model.Name)
</div>
<div class="editor-field">
<input class="text-box single-line required" id="Name" name="Name" type="text" value="" />
</div>
<div class="editor-label">
@Html.LabelFor(Function(model) model.Description)
</div>
<div class="editor-field">
<input class="text-box single-line required" id="Description" name="Description"
type="text" value="" />
</div>
<div class="editor-label">
@Html.LabelFor(Function(model) model.Price)
</div>
<div class="editor-field">
<input class="text-box single-line required" id="Price" name="Price" type="text"
value="" />
</div>
<input id="butSave" type="submit" value="Save" />
<input id="butCancel" type="button" value="Cancel" />
</fieldset>
</form>
</div>
</div>

Most of it are just containers that will be used by the application to display the Product form and the Product Grid. As we go on with the brown bag session I will tackle each of these containers and how to handle them with Jquery.

That was it for now. I hope that this post already gave you an overview of the project. Try to run the project and see the result of the view we've just created. The next post will be on using JqGrid on ASP.NET MVC 3. Stay tune for more!

Jquery AJAX with ASP.NET MVC3

The next series of brown bag sessions is about using Jquery AJAX with ASP.NET MVC 3. This project is the continuation of ASP.NET MVC 3 and Entity Framework Code First project. The methods I used in this project are undocumented. Feel free to apply or modify these tips and tricks to your own project. As we go along with the topic I will include the references of the plug-ins used for you to study and download the source. It is recommended that you enhance the methods and the code structure for production purposes. Greate! Let the learning begin!

Using Jquery AJAX with ASP.NET MVC 3

Brown Bag Sessions - Learning on the go!

First of all, welcome back and thank you for checking out my new blog. The preview URL and Blog Title encountered some issues on cybersquating. Brown Bag seminars, sessions or lunches are generally training or information sessions during a lunch break. It is a symbol of a meal brought along. Pinoy Brown Bag Sessions hope to share some tips and tricks from my programming experience also with random brown bag sessions on interesting topics that we love to share. Pinoy Brown Bag hopes that through these posts you can bring along some knowledge about the best training and tutorials that we can offer. "Sharing is Loving" some of my favorite lines back in my college days.

Their were some comments asking for the source code. I was able to upload one project to my github repository. Unfortunately for some reasons github seems to be offline for the moment and I can't post the link to the project repo. I will continue the topic on ASP.NET MVC in the next post and as soon as the git hub link i available I can share with you the source code of the previews projects. Please email me or post a comment so that I can give you the link.

Socialize! add me up so we can share thoughts.


Brown Bag Sessions - Learning on the go!

First of all, welcome back and thank you for checking out my new blog. The preview URL and Blog Title encountered some issues on cybersquating. Brown Bag seminars, sessions or lunches are generally training or information sessions during a lunch break. It is a symbol of a meal brought along. Pinoy Brown Bag Sessions hope to share some tips and tricks from my programming experience also with random brown bag sessions on interesting topics that we love to share. Pinoy Brown Bag hopes that through these posts you can bring along some knowledge about the best training and tutorials that we can offer. "Sharing is Loving" some of my favorite lines back in my college days.

Their were some comments asking for the source code. I was able to upload one project to my github repository. Unfortunately for some reasons github seems to be offline for the moment and I can't post the link to the project repo. I will continue the topic on ASP.NET MVC in the next post and as soon as the git hub link i available I can share with you the source code of the previews projects. Please email me or post a comment so that I can give you the link.

Socialize! add me up so we can share thoughts.


Saturday, July 9, 2011

Video Tutorial: ASP.NET MVC, EntityFramework Code Frist

I uploaded a video demonstration of the ToyStore project. This project uses the ASP.NET MVC 3 and Entity Framework 4.1 Code First. For more information and discussion of this video, please see my earlier post which discuss the process of creating an ASP.NET MVC 3 project. I also discussed EF Code First which allows you to generate the database based from the created model classes. In the next post I will be discussing my method of integrating Jquery and other Jquery Plug-ins to this framework. 






I hope you've learn a lot from my simple tutorials. Stay tune for more of these topics and the series of articles that I will be posting about ASP.NET MVC 3.

Video Tutorial: ASP.NET MVC, EntityFramework Code Frist

I uploaded a video demonstration of the ToyStore project. This project uses the ASP.NET MVC 3 and Entity Framework 4.1 Code First. For more information and discussion of this video, please see my earlier post which discuss the process of creating an ASP.NET MVC 3 project. I also discussed EF Code First which allows you to generate the database based from the created model classes. In the next post I will be discussing my method of integrating Jquery and other Jquery Plug-ins to this framework. 






I hope you've learn a lot from my simple tutorials. Stay tune for more of these topics and the series of articles that I will be posting about ASP.NET MVC 3.

Simple ASP.NET MVC Create, Edit and Delete Tutorial


In this post I'm going to show you how to do the Create, Edit and Delete function in ASP.NET MVC 3. The previews post thought us how to create our own ASP.NET MVC 3 project for the first time. We used Entity Framework 4.1 Code Frist to create our database from our model class named Product. Let us finish creating the CRUD (Create Read Update Delete) before we proceed on integrating Jquery to our project.




Create

Lets insert the Create Function in the Home Controller. The code snippet is given bellow.

' GET: /Home/Create

Function Create() As ActionResult
Return View()
End Function

'
' POST: /Home/Create

<HttpPost()> _
Function Create(ByVal productToCreate As Product) As ActionResult
Try
' TODO: Add insert logic here
_entities.Products.Add(productToCreate)
_entities.SaveChanges()
Return (RedirectToAction("Index"))
Catch
Return View()
End Try
End Function

Notice that their are two Create functions. The first Create function will return a view which contains the form for creating the product. The second function executes the Linq to Entity function to save the object to the database. Lets create the view for this method. 

1. Right click the first Create function and select Add View.
2. Create a strongly-typed view.
3. Select the model class "ProductDBContext."
4. Select the scaffold template "Create" and then click Add. 



This will generate a view located at Views > Home > Create.vbhtml. You can see that the scaffold method creates the fields of the form according to the model class identified in adding the view. This method shows how ASP.NET MVC 3 manage its views. Figure 1, shows the view created by the scaffold method.

Figure 1. Create Product form generated by MVC 3.

Edit
Just after the Create function in the Home controller, lets insert the Edit function.

' GET: /Home/Edit/5

Function Edit(ByVal id As Integer) As ActionResult
Dim productToEdit = (From p In _entities.Products _
Where p.Id = id _
Select p).FirstOrDefault()
Return View(productToEdit)
End Function

'
' POST: /Home/Edit/5

<HttpPost()> _
Function Edit(ByVal productToEdit As Product) As ActionResult
Try
' TODO: Add update logic here
Dim originalProduct = _entities.Products.Find(productToEdit.Id)
UpdateModel(originalProduct)
_entities.SaveChanges()
Return RedirectToAction("Index")
Catch
Return View()
End Try
End Function

The method of creating the Edit function is the same with the Create function. One function will retrieve the data and  return object to the view. The other function will receive the edited value and execute the query to update the database. To create the view we will follow the same procedure as to the create function.


1. Right click the first Edit function and select Add View.
2. Create a strongly-typed view.
3. Select the model class "ProductDBContext."
4. Select the scaffold template "Edit" and then click Add. 


The scaffold method will then again create a view located at Views > Home > Edit. The view will contain a form that will be used for editing the selected product. Let us test the view by first trying to add a product to our database. I added one product as showed in Figure 2.

Figure 2. The list view showing one product.
The list view we created in the index page is now field with one record. It also includes links to Edit, Details and Delete the record. Let us try out the Edit link. Figure 3 bellow shows how the Edit view is presented.

Figure 3.  Edit view shows the selected record.

The selected record to edit populates the form. Try to edit the record and hit save. The changes will then be updated to the database. After saving the record the page will return to the index by default. Now lets try the next function Details. Figure 4 bellow shows the details of the selected record. This is the Details view that we have created earlier in the previews post. 
Figure 4. Detail view of the selected record.

Delete

To complete the CRUD we insert the Delete function after the Edit function. The code snipped for the Delete function is shown below. 

'
' GET: /Home/Delete/5

Function Delete(ByVal id As Integer) As ActionResult
Dim productToDelete = (From p In _entities.Products _
Where p.Id = id _
Select p).FirstOrDefault()
Return View(productToDelete)
End Function

'
' POST: /Home/Delete/5

<HttpPost()> _
Function Delete(ByVal productToDelete As Product) As ActionResult
Try
' TODO: Add delete logic here
Dim originalProduct = _entities.Products.Find(productToDelete.Id)
_entities.Products.Remove(originalProduct)
_entities.SaveChanges()
_entities.SaveChanges()
Return RedirectToAction("Index")
Catch
Return View()
End Try
End Function

The last Delete function also demonstrates the same concept as to the Create and Edit function. The first function will get the selected object from the database and the second function will execute the query to delete the record from the database. Figure 5 bellow shows selected record to delete. 

Figure 5. Details of the selected file to delete.

Finally we have created our first ASP.NET MVC 3 application with basic CRUD functions. Using the scaffold type views, creating the views for this project was made easy. The last part of the this series is the integration of Jquery and other Jquery plug-ins such as JqGrid, JqPopulate and JqValidate. But before that, the next post will show the video of the ToyStore project we have made in this post. 

Simple ASP.NET MVC Create, Edit and Delete Tutorial


In this post I'm going to show you how to do the Create, Edit and Delete function in ASP.NET MVC 3. The previews post thought us how to create our own ASP.NET MVC 3 project for the first time. We used Entity Framework 4.1 Code Frist to create our database from our model class named Product. Let us finish creating the CRUD (Create Read Update Delete) before we proceed on integrating Jquery to our project.


Thursday, July 7, 2011

Create ASP.NET MVC application with EntityFramework Code Frist

Creating the MVC application

Few days ago I posted a video demo on a simple project using ASP.NET MVC 2 and Jquery. In this post I will be using MVC 3 framework to create a simple Toy Store project. Lets start!

1. In Visual Studio 2010, add a new project by selecting the File>New>Project.
2. At the left side you can see a list of installed templates. Choose the language of your choice and select web.

Figure 1. Create an ASP.NET MVC 3 web application. 

3. Select ASP.NET MVC 3 Web Application using your language of choice. This project will use VB.NET    for the code behind.
4. Name the project ToyStoreMVC3Jquery and then click OK.
5. In the New ASP.NET MVC 3 Project wizard, choose Internet Application, select Razor as your view          engine and click OK. You can also select ASP as your view engine but I would prefer to use Razor.


Congratulations! You just have created your first ASP.NET MVC 3 application. Test the application by running the code you will have the result the same as the image bellow.

Figure 2. Your first ASP.NET MVC 3 application.
In Figure 2, the application already has a template that you can work on. During the creation of the project we selected the Internet Application which provide us with this template. Some people would prefer the empty project template but to omit the cost of time consuming design I prefer to use the available template.

Figure 3. The ToyStoreMVC3Jquery Solution.

The MVC 3 frameworks provides us with a default structure such as shown in Figure 3. One thing that I can point out with this structure is the separation of concern. Each folder identifies a specific role in the application.

M - Model

The M in MVC stands for Model which contains the Domain Classes that identify our entities. Each class is called a model. Let us create a model named Product.



1. Right click on the Models folder located in the Solution Explorer.
2. In the context menu, select Add > Class.
3. Name the class "Product" and click OK.
4. Right click on the project located in the Solution Explorer.
5. In the context menu, select Add Reference.
6. Select the Browse tab and navigate to "C:\Program Files (x86)\Microsoft ADO.NET Entity Framework 4.1\Binaries". Select EntityFramework.dll and click OK.


The code for the product class is written bellow. I have identified five properties of the object product. Bellow the Product class it the ProductDBContext. This class will manage the classes and the database interaction. The Entity Framework will serve as the bridge from our classes to the database. We will use the DbSet Property "Products" to execute database query. This Entity Framework method will return set of Product object instances that we can use in our application.

Product.vb

Imports System.Data.Entity
Imports System.ComponentModel.DataAnnotations

Public Class Product
Public Property Id() As Integer

<required()>
Public Property Name() As String
<required()>
Public Property Description() As String
Public Property Price() As Double
End Class

Public Class ProductDBContext
Inherits DbContext
Public Property Products() As DbSet(Of Product)

Protected Overrides Sub OnModelCreating(ByVal modelBuilder As System.Data.Entity.DbModelBuilder)

End Sub
End Class

Question: Where is the Database? 
Their are three methods that are commonly used nowadays.

  • Database First - This approach allows you to use legacy database in your ORM application. It supposes that you already have existing database and build your entity model based on this database.
  • Model First - This approach supposes creating entity model (its conceptual part), and then generating storage, mapping, and DDL for creating a database schema, based on the storage part of the model. It was implemented in that way in Entity Framework 4.1.
  • Code First -  This method depends on the location of a database. If the database is specified in the configuration, EF will locate the database by default. If the database does not exist, the EF will create the database for you. The default database will be created in the SQL Server Express with the name derived from a strongly typed name of the context.
Sounds great! I will be using the Code First method with SQL Server Express for this project. 


C - Controller

C stands for Controller. This folder contains the logic that will handle our formula and query. In this project the controller will retrieve data from the database and pass the data to the view. In a more advanced application this is not recommended. Separation of logic is very important for complex application. Today, I am using certain pasterns to identify layers for better implementation of separation of concern. Thus, creating a loosely coupled application. 

Index and Details Method

Let us start with the Index and Details method. This is the code for the controller. 

Namespace ToyStoreMVC3Jquery
Public Class HomeController
Inherits System.Web.Mvc.Controller
Private _entities As New ProductDBContext

'
' GET: /Home

Function Index() As ActionResult

Return View(_entities.Products.ToList())
End Function

'
' GET: /Home/Details/5

Function Details(ByVal id As Integer) As ActionResult
Dim result = (From p In _entities.Products _
Where p.Id = id _
Select p).FirstOrDefault()
Return View(result)
End Function
End Class
End Namespace

V - View

Finally, V which stands for View. The view is the presentation layer. This layer is what the user see and interact with. MVC framework allows us to scaffold the view. Lets proceed to understand more about this process.  

1. To create the view for index (the default page of the web application), right click the index function and select Add View.  

2. A dialog box will appear. Check the "Create a strongly-typed view" and select the model class "ProductDBContext(ToyStoreMVC3Jquery).
3. Select the scaffold template "List". Leave the other options and click Add.


We can create the Details view by just repeating the process. This time we select "Details" for the scaffolding template. The process will then generate two files (Index.vbhtml and Details.vbhtml ). These files are located at the Views folder.

Connection String

Next we have to change the connection string to implement Code First. The connection string will provide the link to the SQL Server Express. Open the Web.config and change the <connectionStrings> with this code.


Web.config

<connectionStrings>
<add name="ProductDBContext"
connectionString="Server=.\SQLEXPRESS;Database=ToySotreDB;Trusted_Connection=true"
providerName="System.Data.SqlClient" />
</connectionStrings>

Now we are done with configuration. Lets try to run our application. The expected output is that the EF will generate a database named ToyStoreDB. This database contains a table named Product with the fields that we identified earlier in the Product class. Open your SQL Server Manager and locate ToyStoreDB such as shown in Figure 4. 


Figure 4. ToyStoreDB

In the next post I will present the Create, Edit and Delete Method. 

Create ASP.NET MVC application with EntityFramework Code Frist

Creating the MVC application

Few days ago I posted a video demo on a simple project using ASP.NET MVC 2 and Jquery. In this post I will be using MVC 3 framework to create a simple Toy Store project. Lets start!

1. In Visual Studio 2010, add a new project by selecting the File>New>Project.
2. At the left side you can see a list of installed templates. Choose the language of your choice and select web.

Figure 1. Create an ASP.NET MVC 3 web application. 

3. Select ASP.NET MVC 3 Web Application using your language of choice. This project will use VB.NET    for the code behind.
4. Name the project ToyStoreMVC3Jquery and then click OK.
5. In the New ASP.NET MVC 3 Project wizard, choose Internet Application, select Razor as your view          engine and click OK. You can also select ASP as your view engine but I would prefer to use Razor.


Wednesday, July 6, 2011

ASP.NET MVC, Jquery, EntityFramework CodeFrist: Introduction


This post is part of a series of articles regarding how to Insert, Update and Delete data in the database using LINQ to SQL. Also for this project, I will be working with ASP.NET MVC 3, Jquery and Entity Framework 4.1 Code First. Before we proceed, let me give you an overview of the things that I will use in this project. 

ASP.NET MVC 3

It is a framework for building scalable, stadards-based web applications using well-established design patterns and the power of ASP.NET and the .Net Framework. This new release can also be installed side-by-side with ASP.NET MVC 2. Some of the features of this framework are listed bellow. 


For more details about this framework you can visit the site and download the latest release of ASP.NET MVC 3.

Jquery

"Jquery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development. jQuery is designed to change the way that you write JavaScript0."  - Jquery site
Now here is a good thing. ASP.NET MVC 3 come with the Jquery library. I will show you later on how its done and what are the other Javascript libraries included with the MVC framework. If you want to include Jquery in your project manually then you can download it from the Jquery website for free.

Entity Framework 4.1

"The Entity Framework is Microsoft’s recommended data access technology for new applications. Entity Framework 4.1 brings a set of powerful productivity features, including “Code First” support, the productivity-enhancing DbContext API, and the ability to work with an existing database or have it created automatically." - msdn site
You can visit the Microsoft Developer Network Platforms home page to learn more about Entity Framework 4.1 and download to try if for your self. 

Throughout this project I will be using the recommended release of .NET 4 framework. You can download the installer and upgrade your .NET framework. I have been working with .NET 4 in recent projects and so far its working fine with me. Install the recommended framework and libraries and this tutorial should help you along the way. 

Overview

In this walkthrough you will build pieces of a Toy Store application. The walkthrough will not result in a fully functional application, but instead it will use the blog classes to demonstrate the implementation of the ASP.NET MVC 3, Jquery and EF Code First features. The series of articles will tackle the following:
  • Creating the MVC application. 
  • Define classes to represent the entities of the Toy Store products.
  • Reference the Entity Framework code first assembly.
  • Create a DbContext to manage the Blog classes and data access.
  • Build and ASP.NET MVC 3 application that can insert, update and delete Toy Store products.
  • Integrate Jquery ajax and JqGrid

The action will take place in the next post. Stay tune and watch out for the completion of this project. We will learn many things and maybe you can use this with your own project.

You might also like:

Related Posts Plugin for WordPress, Blogger...