Pages

Wednesday, August 26, 2009

GridView Tips and Tricks using ASP.NET 2.0

Tip 1: Add, Update, Delete Records in a Gridview using SqlDataSource
Tip 2: Paging and Sorting a GridView without Refreshing a Page
Tip 3: Pop-up a Confirmation box before Deleting a row in GridView
Tip 4: Display details of the Row selected in the GridView
Tip 5: Retrieve Details of the Row being Modified in GridView
Tip 6: Retrieve Details of the Row being Deleted in GridView
Tip 7: Cancelling Update and Delete in a GridView
Tip 8: Paging and Sorting in GridView without using Datasource control
Tip 9: Delete Multiple rows in a GridView
Tip 10: Export GridView To Excel

Tuesday, August 25, 2009

Which command will cause an XML file to be generated from documentation comments?

To build the XML Documentation sample within Visual Studio
In Solution Explorer, right-click the project and click Properties. Open the Configuration Properties folder and click Build.
Set the XML Documentation File property to XMLsample.xml.
On the Build menu, click Build.
The XML output file will be in the debug directory.

To build the XML Documentation sample from the Command Line
To generate the sample XML documentation, type the following at the command prompt:csc XMLsample.cs /doc:XMLsample.xml

Monday, August 24, 2009

Send a Calendar Invitation from c# using vCalendar view plaincopy to clipboardprint?

1. using System;
2. using System.Collections.Generic;
3. using System.Text;
4. using System.Net.Mail;
5. using System.IO;
6.
7. namespace CalendaringScheduling
8. {
9. class Program
10. {
11. static void Main(string[] args)
12. {
13. StringBuilder sbCalendar = new StringBuilder();
14. DateTime dtStart = DateTime.Now;
15. DateTime dtEnd = DateTime.Now.AddHours(2);
16.
17. sbCalendar.AppendLine("METHOD: REQUEST");
18. sbCalendar.AppendLine("BEGIN:VCALENDAR");
19. sbCalendar.AppendLine("PRODID:-//Ian Chivers//NET");
20. sbCalendar.AppendLine("MIMEDIR//ENVERSION:1.0");
21. sbCalendar.AppendLine("METHOD:REQUEST");
22. sbCalendar.AppendLine("BEGIN:VEVENT");
23. sbCalendar.AppendLine("DTSTAMP:" + dtStart.ToUniversalTime().ToString("yyyyMMdd\\THHmmss\\Z"));
24. sbCalendar.AppendLine("DTSTART:" + dtStart.ToUniversalTime().ToString("yyyyMMdd\\THHmmss\\Z"));
25. sbCalendar.AppendLine("DTEND:" + dtEnd.ToUniversalTime().ToString("yyyyMMdd\\THHmmss\\Z"));
26. sbCalendar.AppendLine("LOCATION:Minstead");
27. sbCalendar.AppendLine("DESCRIPTION;ENCODING=QUOTED-PRINTABLE:My first meeting");
28. sbCalendar.AppendLine("SUMMARY:Learning Calendaring and Scheduling");
29. sbCalendar.AppendLine("PRIORITY:3");
30. sbCalendar.AppendLine("UID:" + Guid.NewGuid().ToString() + "@ianchivers.com");
31. sbCalendar.AppendLine("ATTENDEE;ROLE=REQ-PARTICIPANT;PARTSTAT=NEEDS-ACTION:MAILTO:ian.chivers@triangle-group.com");
32. sbCalendar.AppendLine("ATTENDEE;ROLE=CHAIR;PARTSTAT=ACCEPTED:MAILTO:ian@ianchivers.com");
33. sbCalendar.AppendLine("CLASS:PUBLIC");
34. sbCalendar.AppendLine("ORGANIZER:MAILTO:ian@ianchivers.com");
35. sbCalendar.AppendLine("SEQUENCE:0");
36. sbCalendar.AppendLine("STATUS:TENTATIVE");
37. sbCalendar.AppendLine("END:VEVENT");
38. sbCalendar.AppendLine("END:VCALENDAR");
39.
40. byte[] byteArray = Encoding.UTF8.GetBytes(sbCalendar.ToString());
41.
42. Stream contentStream = new MemoryStream(byteArray);
43.
44. SmtpClient smtp = new SmtpClient("mx1.hotmail.co.uk");
45. MailMessage memo = new MailMessage("ian@ianchivers.com", "ian_chivers@hotmail.co.uk");
46. Attachment attachment = new Attachment(contentStream, "calendar.ics", "text/calendar");
47. attachment.TransferEncoding = System.Net.Mime.TransferEncoding.Base64;
48. memo.Attachments.Add(attachment);
49. smtp.Send(memo);
50.
51. }
52. }
53. }

Tuesday, August 18, 2009

Microsoft: 'Friends don't let friends use IE6'Microsoft: 'Friends don't let friends use IE6'

Microsoft: 'Friends don't let friends use IE6'
But defends enterprise reluctance to scrap 'albatross' of a browser
By Gregg Keizer
August 17, 2009 03:57 PM ET

* Judge: Microsoft planned to bury i4i
* Three indicted for hack attacks on Heartland, Hannaford
* Twitter: latest application platform problems solved
* G1 Android phone may be unable to receive updates
* EBay gives merchants access to Selling Manager applications
* Microsoft: 'Friends don't let friends use IE6'


Computerworld - Microsoft sympathizes with people pushing what it calls the "Die IE6, Die" campaign, but argued today that it simply can't put a stake in the old browser's heart.

"Friends don't let friends use IE6," said Amy Bazdukas, Microsoft's general manager for Internet Explorer (IE). That sentiment, however, only applies to some people using Windows and the eight-year-old browser -- mainly consumers. "It's certainly part of our approach to consumers to get them to upgrade to IE8," Bazdukas said.

But while she agreed that consumers should ditch IE6, and understood the motivation behind the growing chorus of Web sites calling for an end to the browser, Bazdukas said Microsoft couldn't give the same advice to businesses. "With our business customers, it's more complex," she argued. "For them, deploying a browser is very like much like deploying an operating system across multiple desktops. So it's not a surprise that IE6 is still being used."

Not that Microsoft's entirely happy with that. "IE6 use is higher than we like," Bazdukas admitted. "Most of that is from the business installations, that's where we see most of the trailing installations of IE6."

According to the most recent data from California-based Web metrics company Net Applications, 27.2% of all Internet users are still running IE6, making it the most popular version of IE. By comparison, IE7 accounted for 23.1% of all browsers in action last month, while the newest edition, IE8, had a usage share of 12.5%.

In other words, IE6 accounts for approximately 40% of all instances of Internet Explorer worldwide, beating both IE7 (34%) and IE8 (19%) in "IE market share."

Bazdukas also attributed some of IE6's popularity to Windows' high piracy rates in countries like China and India. "There's a reluctance [among people using counterfeit Windows] to use Automatic Updates," she said, calling out China in particular. "Rather than download updates, often the solution to problems is to re-image the machine using the pirated, pre-XP SP2 counterfeit. That also helps to drive the persistence of IE6."

"I think Microsoft would like to have people upgrade from IE6," said Ray Valdes, an analyst with Gartner. "But the situation is, it's surprisingly difficult to get enterprises to upgrade. Many companies have old software that depends on IE6, and that software is not upgradable because they have no budget or the developer is not around anymore, or the in-house developer left."

Like Bazdukas, Valdes thinks IE6 is ancient history. "I've recommended to clients for the last two years that they get off IE6," Valdes said. "Almost anywhere else is a better place to be."

Bazdukas reiterated what several other Microsoft managers have recently said, that the company is committed to supporting IE6 until April 8, 2014, which is when all support for Windows XP, the operating system IE6 is tied to, will end.

Microsoft shifts gears (again) with its Oslo modeling platform

August 17th, 2009
Microsoft shifts gears (again) with its Oslo modeling platform

Posted by Mary Jo Foley @ 8:06 am

Categories: .Net Framework, Code names, Corporate strategy, Database, Development tools..., PDC 2009, SQL Server, Visual Studio 10 ("Hawaii")

Tags: Team, Oslo, Microsoft Corp., Modeling, Research & Development..., Team Management, Business Operations, Management, Mary Jo Foley
1 TalkBack

It’s been awfully quiet on the Microsoft service-oriented architecture (SOA) front for the past nine months or so. But on August 17, Product Unit Manager Doug Purdy broke the silence to provide an update on Microsoft’s “Oslo” modeling platform and strategy.

The Data Programmability team (which manages Astoria, Entity Data Model (EDM), Entity Framework (EF), XML, ADO.Net and tools/designers) is merging with the Oslo team, Purdy blogged. (The Oslo team has been working on the M language , which was formerly known as “D”; the Quadrant tool; and the modeling repository.)

Purdy blogged:

“What does this mean for you (.NET developers)? You are going hear more about how ‘M’/EF/EDM align. How our VS tools related to ‘Quadrant.’ How this notion of ‘model-drive software’ evolves with the existing .NET FX (Framework) investments. … More to be reveled at PDC (in November in Los Angeles).”

Purdy acknowledged Microsoft officials used the “Oslo” term too broadly when the company first shared its high-level Oslo vision back in 2007. At one point, Microsoft was referring to everything from the next release of its Workflow Framework (WF) and Windows Communication Framework (WCF) 4.0, to its “Dublin” application server, the next release of BizTalk Server, and a future release of SQL Server as all being components of Oslo.

In more recent months, however, the team began shifting its positioning to only use “Oslo” to refer to the modeling pieces of the platform. WF 4.0, WCF 4.0, Dublin and other “.Net 4.0 wave” deliverables, expected to be released in the spring of 2010, are no longer positioned as pieces of Oslo.

So what is Oslo today? Purdy offered this definition back in April:

“The term ‘Oslo’ today refers to a modeling stack — which is just technology jargon for a data stack. We have a language (’M') for writing down other languages, instance data, schemas, expressions and functions. We have a repository (which is just a SQL Server database with a “catalog” in it) for storing data. We have a tool (’Quadrant’) for getting N views (graphical and textual over that data). We have a set of base ‘models’ that people can use and extend to help people write down and access data. We are then taking that stack and working with teams all over Microsoft to move the application lifecycle (design, build, manage) to top of this stack.”

Purdy still isn’t mentioning any ship targets for M, Quadrant or the repository, but maybe now that the team behind those modeling elements is merging with a team shipping discrete tools, Microsoft’s new modeling platform will start trickling out sooner rather than later….

Mary Jo FoleyMary Jo has covered the tech industry for more than 20 years. Don't miss a single post. Subscribe via Email or RSS. You can also follow Mary Jo on Twitter.

Got a tip? Send Mary Jo your rants, rumors, tips and tattles. For disclosure on Mary Jo's industry affiliations, click here or to see Mary Jo's full profile click here.

Monday, August 17, 2009

Standard .Net Development Test For Windows Forms

Standard .Net Development Test

For Windows Forms

This test, which consists of writing a simple utility application written in .Net, is a standard test given to all technical applicants. How we judge this test is based on the job being applied for.

The results of this test will allow us to better understand your thought process when writing an application; Such as design, implementation, usability, as well as your attention to detail.





Overview

The purpose of the application is to allow end-users to quickly enter and manage a list of name/value pairs.

Although this test must be written without any other persons help, any standard reference material that is used during a normal programming cycle may be used (such as online help or books). No third party class libraries or code snippets may be used.

Create a Windows Forms application using a UI similar to the one shown below. The application code should be written in C# , unless you are specifically applying for a position that does not require C# skills or were given instructions to do otherwise.


Required Features:

Name/Value pairs are to be entered into the upper textbox. This textbox will be used by the end-user to quickly add Name/Value pairs to the list below.

When a Name/Value pair is about to be added to the list it must be validated to ensure proper syntax. If the syntax is incorrect then the Name/Value pair must not be added. The Name/Value pair entry format is shown below:

=

Where is the name portion of the pair, and is the value portion of the pair. Only valid Name/Value pairs can be added. Names and Values can contain only alpha-numeric characters. The equal-sign is used to delimit the pair, spaces before and/or after the equal-sign may be entered by the end user (and should be ignored.)

When the ‘Sort by Name’ button is pressed the list will be sorted ascending by Name.

When the ‘Sort by Value’ button is pressed the list will be sorted ascending by Value.

When the ‘Delete’ button is pressed all selected items in the listbox will be deleted.

When the ‘Save as XML’ button is pressed, all of the items in the listbox must be saved to an XML file.

When the ‘Exit’ button is pressed the program will close.

General Information

Make any modifications/additions you feel are necessary to enhance the usability of this application. Some of the descriptions (such as ‘Save to XML’) are kept vague on purpose, to allow you to make your own design/implementation decisions. Keep the code clean, well organized and well commented. The quality of the application should be at the same level that you would to create for a paying client/employer. If you have any questions about the description of the application please feel free to send in an email with your inquiry.

Once the test is complete please zip up the project and its associated files along with a release build of the executable. Then email the zip file in along with a copy of your resume.

Thanks in advance for taking the time to apply at Dundas Software.

Survey Results

Survey Results


What development tools and platforms do you expect to be using and targeting daily within a couple of years?

Survey period: 10 Aug 2009 to 17 Aug 2009

Just when you think you have a grip on one technology, a new one springs up.

What will you be working in and on in a couple of years? (Suggested by Bill)

OptionVotes%
.NET (on any platform, eg Mono)100771.021007 votes, 71.02%
Adobe Flash/Flex/Air1097.69109 votes, 7.69%
C++46132.51461 votes, 32.51%
C#102972.571029 votes, 72.57%
Chrome OS805.6480 votes, 5.64%
Java20014.10200 votes, 14.10%
Javascript44831.59448 votes, 31.59%
Javascript libraries such as jQuery, script.aculo.us, Moo Tools etc.30621.58306 votes, 21.58%
Parallel programming extensions to current tools31322.07313 votes, 22.07%
PHP517612.41176 votes, 12.41%
Ruby on Rails or TurboGear352.4735 votes, 2.47%
SilverLight43330.54433 votes, 30.54%
WPF (possibly with Expression Blend)51536.32515 votes, 36.32%
Something as yet unknown22015.51220 votes, 15.51%
Other1158.11115 votes, 8.11%
Responses1405
1418 votes
This is a multiple choice question. Totals may not add up to 100%

Create a Movie Database Application in 15 Minutes with ASP.NET MVC (C#)

Create a Movie Database Application in 15 Minutes with ASP.NET MVC (C#)

The purpose of this tutorial is to give you a sense of "what it is like" to build an ASP.NET MVC application. In this tutorial, I blast through building an entire ASP.NET MVC application from start to finish. I show you how to build a simple database-driven application that illustrates how you can list, create, and edit database records.

To simplify the process of building our application, we’ll take advantage of the scaffolding features of Visual Studio 2008. We’ll let Visual Studio generate the initial code and content for our controllers, models, and views.

If you have worked with Active Server Pages or ASP.NET, then you should find ASP.NET MVC very familiar. ASP.NET MVC views are very much like the pages in an Active Server Pages application. And, just like a traditional ASP.NET Web Forms application, ASP.NET MVC provides you with full access to the rich set of languages and classes provided by the .NET framework.

My hope is that this tutorial will give you a sense of how the experience of building an ASP.NET MVC application is both similar and different than the experience of building an Active Server Pages or ASP.NET Web Forms application.

Overview of the Movie Database Application

Because our goal is to keep things simple, we’ll build a very simple Movie Database application. Our simple Movie Database application will allow us to do three things:

  1. List a set of movie database records
  2. Create a new movie database record
  3. Edit an existing movie database record

Again, because we want to keep things simple, we’ll take advantage of the minimum number of features of the ASP.NET MVC framework needed to build our application. For example, we won’t be taking advantage of Test-Driven Development.

In order to create our application, we need to complete each of the following steps:

  1. Create the ASP.NET MVC Web Application Project
  2. Create the database
  3. Create the database model
  4. Create the ASP.NET MVC controller
  5. Create the ASP.NET MVC views

Preliminaries

You’ll need either Visual Studio 2008 or Visual Web Developer 2008 Express to build an ASP.NET MVC application. You also need to download the ASP.NET MVC framework.

If you don’t own Visual Studio 2008, then you can download a 90 day trial version of Visual Studio 2008 from this website:

http://msdn.microsoft.com/en-us/vs2008/products/cc268305.aspx

Alternatively, you can create ASP.NET MVC applications with Visual Web Developer Express 2008. If you decide to use Visual Web Developer Express then you must have Service Pack 1 installed. You can download Visual Web Developer 2008 Express with Service Pack 1 from this website:

http://www.microsoft.com/downloads/details.aspx?FamilyId=BDB6391C-05CA-4036-9154-6DF4F6DEBD14&displaylang=en

After you install either Visual Studio 2008 or Visual Web Developer 2008, you need to install the ASP.NET MVC framework. You can download the ASP.NET MVC framework from the following website:

http://www.asp.net/mvc/

Instead of downloading the ASP.NET framework and the ASP.NET MVC framework individually, you can take advantage of the Web Platform Installer. The Web Platform Installer is an application that enables you to easily manage the installed applications are your computer:

http://www.microsoft.com/web/gallery/Install.aspx

Creating an ASP.NET MVC Web Application Project

Let’s start by creating a new ASP.NET MVC Web Application project in Visual Studio 2008. Select the menu option File, New Project and you will see the New Project dialog box in Figure 1. Select C# as the programming language and select the ASP.NET MVC Web Application project template. Give your project the name MovieApp and click the OK button.

Figure 01: The New Project dialog box (Click to view full-size image)

Make sure that you select .NET Framework 3.5 from the dropdown list at the top of the New Project dialog or the ASP.NET MVC Web Application project template won’t appear.

Whenever you create a new MVC Web Application project, Visual Studio prompts you to create a separate unit test project. The dialog in Figure 2 appears. Because we won’t be creating tests in this tutorial because of time constraints (and, yes, we should feel a little guilty about this) select the No option and click the OK button.

Visual Web Developer does not support test projects.

Figure 02: The Create Unit Test Project dialog (Click to view full-size image)

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 Movie Database application.

When you create a new MVC application with Visual Studio, you get a sample application. Because we want to start from scratch, we need to delete the content for this sample application. You need to delete the following file and the following folder:

  • Controllers\HomeController.cs
  • Views\Home

Creating the Database

We need to create a database to hold our movie database records. Luckily, Visual Studio includes a free database named SQL Server Express. Follow these steps to create the database:

  1. Right-click the App_Data folder in the Solution Explorer window and select the menu option Add, New Item.
  2. Select the Data category and select the SQL Server Database template (see Figure 3).
  3. Name your new database MoviesDB.mdf and click the Add button.

After you create your database, you can connect to the database by double-clicking the MoviesDB.mdf file located in the App_Data folder. Double-clicking the MoviesDB.mdf file opens the Server Explorer window.

The Server Explorer window is named the Database Explorer window in the case of Visual Web Developer.

Figure 03: Creating a Microsoft SQL Server Database (Click to view full-size image)

Next, we need to create a new database table. From within the Sever Explorer window, right-click the Tables folder and select the menu option Add New Table. Selecting this menu option opens the database table designer. Create the following database columns:

Column Name Data Type Allow Nulls
Id Int False
Title Nvarchar(100) False
Director Nvarchar(100) False
DateReleased DateTime False

The first column, the Id column, has two special properties. First, you need to mark the Id column as the primary key column. After selecting the Id column, click the Set Primary Key button (it is the icon that looks like a key). Second, you need to mark the Id column as an Identity column. In the Column Properties window, scroll down to the Identity Specification section and expand it. Change the Is Identity property to the value Yes. When you are finished, the table should look like Figure 4.

Figure 04: The Movies database table (Click to view full-size image)

The final step is to save the new table. Click the Save button (the icon of the floppy) and give the new table the name Movies.

After you finish creating the table, add some movie records to the table. Right-click the Movies table in the Server Explorer window and select the menu option Show Table Data. Enter a list of your favorite movies (see Figure 5).

Figure 05: Entering movie records (Click to view full-size image)

Creating the Model

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.

The ASP.NET MVC framework is not tied to the Microsoft Entity Framework. You can create your database model classes by taking advantage of a variety of Object Relational Mapping (OR/M) tools including LINQ to SQL, Subsonic, and NHibernate.

Follow these steps to launch the Entity Data Model Wizard:

  1. Right-click the Models folder in the Solution Explorer window and the select the menu option Add, New Item.
  2. Select the Data category and select the ADO.NET Entity Data Model template.
  3. Give your data model the name MoviesDBModel.edmx and click the Add button.

After you click the Add button, the Entity Data Model Wizard appears (see Figure 6). Follow these steps to complete the wizard:

  1. In the Choose Model Contents step, select the Generate from database option.
  2. In the Choose Your Data Connection step, use the MoviesDB.mdf data connection and the name MoviesDBEntities for the connection settings. Click the Next button.
  3. In the Choose Your Database Objects step, expand the Tables node, select the Movies table. Enter the namespace MovieApp.Models and click the Finish button.

Figure 06: Generating a database model with the Entity Data Model Wizard (Click to view full-size image)

After you complete the Entity Data Model Wizard, the Entity Data Model Designer opens. The Designer should display the Movies database table (see Figure 7).

Figure 07: The Entity Data Model Designer (Click to view full-size image)

We need to make one change before we continue. The Entity Data Wizard generates a model class named Movies that represents the Movies database table. Because we’ll use the Movies class to represent a particular movie, we need to modify the name of the class to be Movie instead of Movies (singular rather than plural).

Double-click the name of the class on the designer surface and change the name of the class from Movies to Movie. After making this change, click the Save button (the icon of the floppy disk) to generate the Movie class.

Creating the ASP.NET MVC Controller

The next step is to create the ASP.NET MVC controller. A controller is responsible for controlling how a user interacts with an ASP.NET MVC application.

Follow these steps:

  1. In the Solution Explorer window, right-click the Controllers folder and select the menu option Add, Controller.
  2. In the Add Controller dialog, enter the name HomeController and check the checkbox labeled Add action methods for Create, Update, and Details scenarios (see Figure 8).
  3. Click the Add button to add the new controller to your project.

After you complete these steps, the controller in Listing 1 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 methods to work.

Figure 08: Adding a new ASP.NET MVC Controller (Click to view full-size image)

Listing 1 – Controllers\HomeController.cs

    using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

using System.Web.Mvc.Ajax;

namespace MovieApp.Controllers

{

public class HomeController : Controller

{

//

// GET: /Home/

public ActionResult Index()

{

return View();

}

//

// GET: /Home/Details/5

public ActionResult Details(int id)

{

return View();

}

//

// GET: /Home/Create

public ActionResult Create()

{

return View();

}

//

// POST: /Home/Create

[AcceptVerbs(HttpVerbs.Post)]

public ActionResult Create(FormCollection collection)

{

try

{

// TODO: Add insert logic here

return RedirectToAction("Index");

}

catch

{

return View();

}

}

//

// GET: /Home/Edit/5

public ActionResult Edit(int id)

{

return View();

}

//

// POST: /Home/Edit/5

[AcceptVerbs(HttpVerbs.Post)]

public ActionResult Edit(int id, FormCollection collection)

{

try

{

// TODO: Add update logic here

return RedirectToAction("Index");

}

catch

{

return View();

}

}

}

}

Listing Database Records

The Index() method of the Home controller is the default method for an ASP.NET MVC application. When you run an ASP.NET MVC 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 Movies database table. We’ll take advantage of the database model classes that we created earlier to retrieve the movie database records with the Index() method.

I’ve modified the HomeController class in Listing 2 so that it contains a new private field named _db. The MoviesDBEntities class represents our database model and we’ll use this class to communicate with our database.

I’ve also modified the Index() method in Listing 2. The Index() method uses the MoviesDBEntities class to retrieve all of the movie records from the Movies database table. The expression _db.MovieSet.ToList() returns a list of all of the movie records from the Movies database table.

The list of movies is passed to the view. Anything that gets passed to the View() method gets passed to the view as view data.

Listing 2 – Controllers/HomeController.cs (modified Index method)

    using System.Linq;

using System.Web.Mvc;

using MovieApp.Models;

namespace MovieApp.Controllers

{

public class HomeController : Controller

{

private MoviesDBEntities _db = new MoviesDBEntities();

public ActionResult Index()

{

return View(_db.MovieSet.ToList());

}

}

}

The Index() method returns a view named Index. We need to create this view to display the list of movie database records. Follow these steps:

You should build your project (select the menu option Build, Build Solution) before opening the Add View dialog or no classes will appear in the View data class dropdown list.

  1. Right-click the Index() method in the code editor and select the menu option Add View (see Figure 9).
  2. In the Add View dialog, verify that the checkbox labeled Create a strongly-typed view is checked.
  3. From the View content dropdown list, select the value List.
  4. From the View data class dropdown list, select the value MovieApp.Models.Movie.
  5. Click the Add button to create the new view (see Figure 10).

After you complete these steps, a new view named Index.aspx is added to the Views\Home folder. The contents of the Index view are included in Listing 3.

Figure 09: Adding a view from a controller action (Click to view full-size image)

Figure 10: Creating a new view with the Add View dialog (Click to view full-size image)

Listing 3 – Views\Home\Index.aspx

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



Index





Index



















<% foreach (var item in Model) { %>



















<% } %>



Id



Title



Director



DateReleased



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

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



<%= Html.Encode(item.Id) %>



<%= Html.Encode(item.Title) %>



<%= Html.Encode(item.Director) %>



<%= Html.Encode(String.Format("{0:g}", item.DateReleased)) %>





<%= Html.ActionLink("Create New", "Create") %>






The Index view displays all of the movie records from the Movies database table within an HTML table. The view contains a foreach loop that iterates through each movie represented by the ViewData.Model property. If you run your application by hitting the F5 key, then you’ll see the web page in Figure 11.

Figure 11: The Index view (Click to view full-size image)

Creating New Database Records

The Index view that we created in the previous section includes a link for creating new database records. Let’s go ahead and implement the logic and create the view necessary for creating new movie database records.

The Home controller contains two methods named Create(). The first Create() method has no parameters. This overload of the Create() method is used to display the HTML form for creating a new movie database record.

The second Create() method has a FormCollection parameter. This overload of the Create() method is called when the HTML form for creating a new movie is posted to the server. Notice that this second Create() method has an AcceptVerbs attribute that prevents the method from being called unless an HTTP POST operation is performed.

This second Create() method has been modified in the updated HomeController class in Listing 4. The new version of the Create() method accepts a Movie parameter and contains the logic for inserting a new movie into the Movies database table.

Notice the Bind attribute. Because we don’t want to update the Movie Id property from HTML form, we need to explicitly exclude this property.

Listing 4 – Controllers\HomeController.cs (modified Create method)

    //

// GET: /Home/Create

public ActionResult Create()

{

return View();

}

//

// POST: /Home/Create

[AcceptVerbs(HttpVerbs.Post)]

public ActionResult Create([Bind(Exclude="Id")] Movie movieToCreate)

{

if (!ModelState.IsValid)

return View();

_db.AddToMovieSet(movieToCreate);

_db.SaveChanges();

return RedirectToAction("Index");

}

Visual Studio makes it easy to create the form for creating a new movie database record (see Figure 12). Follow these steps:

  1. Right-click the Create() method in the code editor and select the menu option Add View.
  2. Verify that the checkbox labeled Create a strongly-typed view is checked.
  3. From the View content dropdown list, select the value Create.
  4. From the View data class dropdown list, select the value MovieApp.Models.Movie.
  5. Click the Add button to create the new view.

Figure 12: Adding the Create view (Click to view full-size image)

Visual Studio generates the view in Listing 5 automatically. This view contains an HTML form that includes fields that correspond to each of the properties of the Movie class.

Listing 5 – Views\Home\Create.aspx

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



Create





Create



<%= Html.ValidationSummary("Create was unsuccessful. Please correct the errors and try again.") %>

<% using (Html.BeginForm()) {%>



Fields





<%= Html.TextBox("Id") %>

<%= Html.ValidationMessage("Id", "*") %>







<%= Html.TextBox("Title") %>

<%= Html.ValidationMessage("Title", "*") %>







<%= Html.TextBox("Director") %>

<%= Html.ValidationMessage("Director", "*") %>







<%= Html.TextBox("DateReleased") %>

<%= Html.ValidationMessage("DateReleased", "*") %>











<% } %>



<%=Html.ActionLink("Back to List", "Index") %>




The HTML form generated by the Add View dialog generates an Id form field. Because the Id column is 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 Movie records to the database. Run your application by pressing the F5 key and click the Create New link to see the form in Figure 13. If you complete and submit the form, a new movie database record is created.

Notice that you get form validation automatically. If you neglect to enter a release date for a movie, or you enter an invalid release date, then the form is redisplayed and the release date field is highlighted.

Figure 13: Creating a new movie database record (Click to view full-size image)

Editing Existing Database Records

In the previous sections, we discussed how you can list and create new database records. In this final section, we discuss how you can edit existing database records.

First, we need to generate the Edit form. This step is easy since Visual Studio will generate the Edit form for us automatically. Open the HomeController.cs class in the Visual Studio code editor and follow these steps:

  1. Right-click the Edit() method in the code editor and select the menu option Add View (see Figure 14).
  2. Check the checkbox labeled Create a strongly-typed view.
  3. From the View content dropdown list, select the value Edit.
  4. From the View data class dropdown list, select the value MovieApp.Models.Movie.
  5. Click the Add button to create the new view.

Completing these steps adds a new view named Edit.aspx to the Views\Home folder. This view contains an HTML form for editing a movie record.

Figure 14: Adding the Edit view (Click to view full-size image)

The Edit view contains an HTML form field that corresponds to the Movie Id property. Because you don’t want people editing the value of the Id property, you should remove this form field.

Finally, we need to modify the Home controller so that it supports editing a database record. The updated HomeController class is contained in Listing 6.

Listing 6 – Controllers\HomeController.cs (Edit methods)

    //

// GET: /Home/Edit/5

public ActionResult Edit(int id)

{

var movieToEdit = (from m in _db.MovieSet

where m.Id == id

select m).First();

return View(movieToEdit);

}

//

// POST: /Home/Edit/5

[AcceptVerbs(HttpVerbs.Post)]

public ActionResult Edit(Movie movieToEdit)

{

var originalMovie = (from m in _db.MovieSet

where m.Id == movieToEdit.Id

select m).First();

if (!ModelState.IsValid)

return View(originalMovie);

_db.ApplyPropertyChanges(originalMovie.EntityKey.EntitySetName, movieToEdit);

_db.SaveChanges();

return RedirectToAction("Index");

}

In Listing 6, I’ve added additional logic to both overloads of the Edit() method. The first Edit() method returns the movie database record that corresponds to the Id parameter passed to the method. The second overload performs the updates to a movie record in the database.

Notice that you must retrieve the original movie, and then call ApplyPropertyChanges(), to update the existing movie in the database.

Summary

The purpose of this tutorial was to give you a sense of the experience of building an ASP.NET MVC application. I hope that you discovered that building an ASP.NET MVC web application is very similar to the experience of building an Active Server Pages or ASP.NET application.

In this tutorial, we examined only the most basic features of the ASP.NET MVC framework. In future tutorials, we dive deeper into topics such as controllers, controller actions, views, view data, and HTML helpers.