Create a Strongly Typed CRUD UI With ASP.Net MVC RC
Create a Strongly Typed CRUD UI With ASP.Net MVC RC
In this post I will show the tooling enhancements in ASP.Net MVC that lets you build CRUD (List, Details, Create and Edit) actions very fast. With a little amount of code we can create a good starting point for building a data entry application using ASP.Net MVC.
1. Prepare the database. In this sample I am using the Leasing database, that contains 3 tables. Download the schema and create the database.
2. Create a new ASP.Net MVC Application.
3. Create the Model. In this samples I am using LINQ to SQL, but you can choose any other business object representation. Add a new LINQ to SQL Data Model to the Model folder in the MVC application project, and drag the relevant tables from the Server Explorer into the ORM Designer. This creates classes that represent the tables and relationships in the database.
4. Create a new controller. Right click the Controllers folder in the MVC application, choose Add and select the Controller item.
Provide a name for the controller, check the “Add action methods for Create, Update and Details scenarios”, and click Add.
This creates a new controller, and creates the methods for the above actions. We will explore those actions as we move on.
5. Add a link to the Vehicles module. Open the master page (Site.Master under the Views\Shared folder), and locate the links for Home and About.
<li><%= Html.ActionLink("Home", "Index", "Home")%></li>
<li><%= Html.ActionLink("About", "About", "Home")%></li>
Add a third link to the Vehicles module:
<li><%= Html.ActionLink("Vehicles", "Index", "Vehicles")%></li>
Now, If you run the application, you should see a link on the upper menu.
Implement the List Action: Display a list of Model Items (Vehicles)
1. Create a member of type VehiclesDataContext in the controller. We will use this context to access the database.
public class VehiclesController : Controller
{
VehiclesDataContext db = new VehiclesDataContext();
//
// GET: /Vehicles/
...
}
2. In the Index method, query the database for the list of vehicles using a LINQ query. Then, return a view with the results.
// GET: /Vehicles/
public ActionResult Index()
{
var query = from v in db.Vehicles
select v;
return View(query);
}
3. Create a corresponding View. Right click the code editor somewhere inside this method and choose the Add View context item.
This will open the Add View dialog that lets you choose the view properties before it is generated. In this dialog, check “Create strongly-typed view” and select the Vehicle class from the List. Then, in the View content field, select List.
After you click Add, Visual Studio will generate a view that displays a table with the vehicles details.
If you now run the project, and click the Vehicles link in the top menu, you should get a list of vehicles like this one:
Implement the Details Action: Display the details of a Model Item (Vehicle)
1. In the controller’s Details method, use the id parameter to query the database for the specific vehicle. Then, return a view with the result.
// GET: /Vehicles/Details/5
public ActionResult Details(int id)
{
Vehicle v = db.Vehicles.Single(vh => vh.VehicleID == id);
return View(v);
}
2. Create a corresponding View. Right click the code editor, and select the Add View option. In the dialog, make sure that it is strongly-typed and the View content is Details.
3. Link from the list view to the details view. Each row in the list view had a Details link. To pass the id of the vehicle to the details action, open the Index view (Views\Vehicles\Index.aspx) and locate the Details and Edit links:
<td>
<%= Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) %> |
<%= Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ })%>
</td>
Remove the comment from the third parameter of the ActionLink, and pass the vehicle ID:
<td>
<%= Html.ActionLink("Edit", "Edit", new { id = item.VehicleID }) %> |
<%= Html.ActionLink("Details", "Details", new { id = item.VehicleID })%>
</td>
4. Run the application, and click the Vehicles link to display a list of vehicles. Then click on the Details link of the first vehicle to display its details.
Implement the Edit Action: Edit the details of a Model Item (Vehicle)
1. Notice that the controller has 2 overloads of the Edit action:
// GET: /Vehicles/Edit/5
public ActionResult Edit(int id)
{
...
}
// POST: /Vehicles/Edit/5
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(int id, FormCollection collection)
{
...
}
The first one is for getting the vehicle details in order to display then in the View. When the user clicks the submit button, a POST message will call the second overload with the form data.
2. Get the details of the vehicle to display in the view. This implementation is identical to the Display action implementation.
// GET: /Vehicles/Edit/5
public ActionResult Edit(int id)
{
Vehicle v = db.Vehicles.Single(vh => vh.VehicleID == id);
return View(v);
}
3. Create a corresponding view, and make sure to select Edit as the View content.
4. Implement the Save action. In the second overload of the Edit method, get the data out of the FormCollection instance, and apply it the the vehicle. Then save the changes to the DB, and display the list.
// POST: /Vehicles/Edit/5
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(int id, FormCollection collection)
{
Vehicle v = db.Vehicles.Single(vh => vh.VehicleID == id);
v.Cargo = int.Parse(collection["Cargo"]);
v.Category = int.Parse(collection["Category"]);
v.MaxSpeed = int.Parse(collection["MaxSpeed"]);
...
db.SubmitChanges();
return RedirectToAction("Index");
}
5. Enable the Edit link in the Details View. Open the Details View (Views\Vehicles\Details.aspx) and locate the Edit link at the bottom. Then, remove the comment from the third parameter of the ActionLink, and pass the vehicle ID:
<%=Html.ActionLink("Edit", "Edit", new { id = Model.VehicleID }) %>
5. Run the application, and click the Vehicles link to display a list of vehicles. Then, click on the Edit link of the first vehicle to display its details for editing:
Change the values of the vehicle and click Save. The updated values will be displayed in the list of vehicles.
Implement the Create Action: Create a new Model Item (Vehicle)
1. Notice that the Create method has 2 overloads as well. Again, one is to do any work before the Create View is shown and the other is to respond to the POST message and insert the data to the database.
2. Create the Create View using the Add View context item in the code editor. Make sure to select Create in the View content. In this sample you don’t have to change the logic in the Create method, since no data is necessary for creating a new vehicle.
3. Implement the second overload of the Create method. Extract the data from the FormCollection instance, and build a new instance of Vehicle. Then, add it to the database, and return to the list.
// GET: /Vehicles/Create
public ActionResult Create()
{
return View();
}
// POST: /Vehicles/Create
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(FormCollection collection)
{
Vehicle v = new Vehicle
{
MaxSpeed = int.Parse(collection["MaxSpeed"]),
Model = collection["Model"],
...
};
db.Vehicles.InsertOnSubmit(v);
db.SubmitChanges();
return RedirectToAction("Index");
}
4. Run the application, and click the Vehicles link to display a list of vehicles. Then, scroll to the buttom of the page and click on the Create New link. This will show a new form that collects the details of a vehicle.
Once you filled the data, click Create, and the new vehicle will be displayed in the list.
Conclusion
The tooling enhancements in ASP.Net MVC RC makes creating CRUD (List, Details, Create and Edit) actions very fast. With a little amount of code we have created a good starting point for building a data entry application using ASP.Net MVC.
Enjoy!
Comments
- Anonymous
February 02, 2009
PingBack from http://www.clickandsolve.com/?p=3088 - Anonymous
February 03, 2009
Thank you for submitting this cool story - Trackback from DotNetShoutout - Anonymous
April 04, 2011
Thank you so much... It is helpful for me to learn MVC