Biodata ba 'kamo? end term requirement in elective 4 2 3 FEB 2014 C RUD (Create, Update, Delete) Operations + Searching in MVC 2 (VB) posted in biodata, CRUD, MVC, searching, VB by joannamarielm This article describes how to perform basic CRUD (Create, Update, Delete) operations + Searching in an MVC 2 application using Entity Framework 4. The purpose of this tutorial is to give a sense of “what it is like” to build an ASP.NET MVC application. In this tutorial, we’ll show you how to build a simple database-driven application that illustrates how you can list, create, delete, and edit database records. But first, let’s have a short introduction about MVC and Entity Framework. I. MVC Model: is an object representing data or even activity, e.g. a database table or even some plant-floor production-machine process. View: is some form of visualization of the state of the model. Controller: offers facilities to change the state of the model. To implement MVC in .NET we need mainly three classes (View, Controller and the Model). II. ENTITY FRAMEWORK Let’s have a look at the standard definition of Entity Framework given by Microsoft: “The Microsoft ADO.NET Entity Framework is an Object/Relational Mapping (ORM) framework that enables developers to work with relational data as domain-specific objects, eliminating the need for most of the data access plumbing code that developers usually need to write. Using the Entity Framework, developers issue queries using LINQ, then retrieve and manipulate data as strongly typed objects. The Entity Framework’s ORM implementation provides services like change tracking, identity resolution, lazy loading, and query translation so that developers can focus on their application-specific business logic rather than the data access fundamentals.” In simple terms, Entity Framework is an Object/Relational Mapping (ORM) framework. It is an enhancement to ADO.NET, an upper layer to ADO.Net that gives developers an automated mechanism for accessing and storing the data in the database.
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Biodata ba 'kamo?
end term requirement in elective 4
23FEB2014
CRUD (Create, Update, Delete) Operations +
Searching in MVC 2 (VB)
posted in biodata, CRUD, MVC, searching, VB by joannamarielm
This article describes how to perform basic CRUD (Create, Update, Delete) operations + Searching inan MVC 2 application using Entity Framework 4.
The purpose of this tutorial is to give a sense of “what it is like” to build an ASP.NET MVC application.In this tutorial, we’ll show you how to build a simple database-driven application that illustrates how
you can list, create, delete, and edit database records. But first, let’s have a short introduction aboutMVC and Entity Framework.
I. MVC
Model: is an object representing data or even activity, e.g. a database table or even some plant-floorproduction-machine process.
View: is some form of visualization of the state of the model.
Controller: offers facilities to change the state of the model.
To implement MVC in .NET we need mainly three classes (View, Controller and the Model).
II. ENTITY FRAMEWORK
Let’s have a look at the standard definition of Entity Framework given by Microsoft:
“The Microsoft ADO.NET Entity Framework is an Object/Relational Mapping (ORM) framework that
enables developers to work with relational data as domain-specific objects, eliminating the need formost of the data access plumbing code that developers usually need to write. Using the Entity
Framework, developers issue queries using LINQ, then retrieve and manipulate data as strongly typedobjects. The Entity Framework’s ORM implementation provides services like change tracking, identityresolution, lazy loading, and query translation so that developers can focus on their application-specific
business logic rather than the data access fundamentals.”
In simple terms, Entity Framework is an Object/Relational Mapping (ORM) framework. It is anenhancement to ADO.NET, an upper layer to ADO.Net that gives developers an automatedmechanism for accessing and storing the data in the database.
III. OVERVIEW OF THE BIODATA DATABASE APPLICATION
Because our goal is to keep things simple, we’ll build a very simple Biodata Database application. Oursimple Biodata Database application will allow us to do three things:
List a set of biodata database recordsCreate a new biodata database record
Edit an existing biodata database recordDelete an existing biodata database recordSearch for an existing biodata database record
Viewing of Biodata
In order to create our application, we need to complete each of the following steps:
Create the ASP.NET MVC Web Application Project
Create the databaseCreate the database model
Create the ASP.NET MVC controllerCreate the ASP.NET MVC views
IV. PRELIMINARIES
Microsoft Visual Studio 2010SQL Server Management Studio Express
V. CRUD (Create, Update, Delete) Operations + Searching in MVC 2 (VB)
Creating a New ASP.NET MVC 2 WEB APPLICATION
Let’s start by creating a new ASP.NET MVC 2 Web Application project in Visual Studio 2010. Selectthe menu option File, New Project and you will see the New Project dialog box. Select Visual Basic asthe programming language and select the ASP.NET MVC Web Application project template. Give your
project the name BiodataSampleApplication and click the OK buDon.
Whenever you create a new MVC 2 Web Application project, Visual Studio prompts you to create aseparate unit test project. The dialog below appears. Because we won’t be creating tests in this tutorial,
An ASP.NET MVC application has a standard set of folders: a Models, Views, and Controllers folder.You can see this standard set of folders in the Solution Explorer window. We’ll need to add files to each
of the Models, Views, and Controllers folders in order to build our Biodata Database application.
When you create a new MVC application with Visual Studio, you get a sample application. Because wewant to start from scratch, we need to delete the content for this sample application. You need todelete the following file and the following folder:
The first column, the Id column, has two special properties. First, you need to mark the Id column asthe primary key column. After selecting the Id column, click the Set Primary Key buDon (it is the icon
that looks like a key). Second, you need to mark the Id column as an Identity column. In the ColumnProperties window, scroll down to the Identity Specification section and expand it. Change the IsIdentity property to the value Yes. When you are finished, the table should look like the one above.
The final step is to save the new table. Click the Save buDon (the icon of the floppy) and give the new
table the name BioTB.
After you finish creating the table, add some records to the table. Right-click the BioTB table in the
Server Explorer window and select the menu option Open Table and enter some records.
We next need to create a set of classes to represent our database. We need to create a database model.We’ll take advantage of the Microsoft Entity Framework to generate the classes for our database model
automatically.
Follow these steps to launch the Entity Data Model Wizard:
Right-click the Models folder in the Solution Explorer window and the select the menu option Add,
New Item.
1.
Select the Data category and select the ADO.NET Entity Data Model template.2.
Give your data model the name BioDBModel.edmx and click the Add buDon.3.
The next step is to create the ASP.NET MVC controller. A controller is responsible for controlling howa user interacts with an ASP.NET MVC application.
Follow these steps:
In the Solution Explorer window, right-click the Controllers folder and select the menu option Add,
Controller.
1.
In the Add Controller dialog, enter the name HomeController and check the checkbox labeled Add
action methods for Create, Update, and Details scenarios.
2.
Click the Add buDon to add the new controller to your project.3.
After you complete these steps, the controller is created. Notice that it contains methods named Index,
Details, Create, and Edit. In the following sections, we’ll add the necessary code to get these methodsto work.
Listing Database Records
The Index() method of the Home controller is the default method for an ASP.NET MVC 2 application.When you run an ASP.NET MVC 2 application, the Index() method is the first controller method that
is called.
We’ll use the Index() method to display the list of records from the BioTB database table. We’ll takeadvantage of the database model classes that we created earlier to retrieve the movie database recordswith the Index() method.
I’ve modified the HomeController class so that it contains a new private field named _db. The
BioEntities class represents our database model and we’ll use this class to communicate with ourdatabase.
I’ve also modified the Index() method. The Index() method uses the BioEntities class to retrieve all ofthe movie records from the Movies database table. The expression _db.BioTBs.ToList() returns a list of
all of the records from the database table.
The list of records is passed to the view. Anything that gets passed to the View() method gets passed tothe view as view data.
The Index() method returns a view named Index. We need to create this view to display the list ofmovie database records. Follow these steps:
You should build your project (select the menu option Build, Build Solution) before opening the AddView dialog or no classes will appear in the View data class dropdown list.
Right-click the Index() method in the code editor and select the menu option Add View.1.
In the Add View dialog, verify that the checkbox labeled Create a strongly-typed view is checked.2.
From the View content dropdown list, select the value List.3.
From the View data class dropdown list, select the value BiodataSampleApplication.BioTB.4.
12345678
Public Class HomeControllerInherits System.Web.Mvc.ControllerPrivate _db As New BioEntities()'' GET: /HomeFunction Index(ByVal searchString As String) As ActionResultReturn View(_db.BioTBs.ToList())End Function
After you complete these steps, a new view named Index.aspx is added to the Views\Home folder.
The Index view displays all of the records from the database table within an HTML table. The viewcontains a For Each loop that iterates through each movie represented by the ViewData.Modelproperty. If you run your application by hiDing the F5 key, then you’ll see the web page like the one
below. Since we have many fields, the table extends outside the main body portion of our project.
To solve this, I modified the Index.aspx and deleted some of the fields. Don’t worry because deletingthem from Index.aspx won’t delete them from the database. In order to view the whole record of eachperson, I added a View link that redirects to another page which displays all the information of each
The HTML form generated by the Add View dialog generates an Id form field. Because the Id columnis an Identity column, we don’t need this form field and you can safely remove it.
After you add the Create view, you can add new records to the database. Press the F5 key and click theCreate New link to see the create form. If you complete and submit the form, a new database record is
The first Edit() method returns the database record that corresponds to the Id parameter passed to themethod. The second overload performs the updates to a record in the database.
123456789101112131415161718
'' GET: /Home/Edit/5
Function Edit(ByVal id As Integer) As ActionResultDim bio As BioTB = _db.BioTBs.Single(Function(a) a.id = id)Return View(bio)End Function
'' POST: /Home/Edit/5
<HttpPost()> _Function Edit(ByVal id As Integer, ByVal collection As FormCollection) As ActionResultDim bio As BioTB = _db.BioTBs.Single(Function(a) a.id = id)UpdateModel(bio)_db.SaveChanges()Return RedirectToAction("Index")End Function
First, we need to generate the Delete form. This step is easy since Visual Studio will also generate theDelete form for us automatically. Open the HomeController.vb class in the Visual Studio code editorand follow the following steps:
Right-click the Delete() method in the code editor and select the menu option Add View.1.
Check the checkbox labeled Create a strongly-typed view.2.
From the View content dropdown list, select the value Delete.3.
From the View data class dropdown list, select the value BiodataSampleApplication.BioTB.4.
</pre>Function UploadPhoto() As ActionResultFor Each Upload As String In Request.FilesDim path As String = AppDomain.CurrentDomain.BaseDirectory + "Images/"Dim filename As String = System.IO.Path.GetFileName(Request.Files(Upload).FileName)Request.Files(Upload).SaveAs(System.IO.Path.Combine(path, filename))Dim dbconn As New SqlClient.SqlConnection("Data Source=JOANNA-PC;Initial Catalog=joanna;IntegrDim comm As New SqlClient.SqlCommand("UPDATE BioTB SET pic='" & filename.ToString & "' WHERE idbconn.Open()comm.ExecuteNonQuery()dbconn.Close()NextReturn RedirectToAction("Index")End Function<pre>
To make it more presentable, I downloaded a template (Curriculum Vitae Template since I had troublefinding Biodata Template), and modified it. Credits to the owner of the CSS template. Sorry, I forgotwhich site I got it from.
#contactDetails ul {list-style-type: none;font-size: 0.9em;margin-top: 2px;}
#contactDetails ul li {margin-bottom: 3px;color: #444;}
#contactDetails ul li a, a[href^=tel] {color: #444;text-decoration: none;-webkit-transition: all .3s ease-in;-moz-transition: all .3s ease-in;-o-transition: all .3s ease-in;-ms-transition: all .3s ease-in;transition: all .3s ease-in;}
#contactDetails ul li a:hover {color: #cf8a05;}section {border-top: 1px solid #dedede;padding: 20px 0 0;}