15.02.2015 Views

C# 4 and .NET 4

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

1272 ❘ ChaPTer 42 Asp.net dynAmic dAtA And mvc<br />

Next, note that a property called ModelState.IsValid is used to check that the model passed to the<br />

method is valid, <strong>and</strong> if not the method simply returns the create view with no parameters. If this happens,<br />

the validation summary <strong>and</strong> validation errors will be displayed, as shown in Figure 42-15.<br />

figure 42-15<br />

If there are no errors, the new item is added through the ADO.<strong>NET</strong> Entity Framework-defined<br />

AddToProducts() method, <strong>and</strong> the page redirects to the list view as follows:<br />

entities.AddToProducts(productToCreate);<br />

entities.SaveChanges();<br />

return RedirectToAction("Index");<br />

An important point to note here is that the validation can be controlled through data annotations,<br />

introduced earlier in the chapter. Most of the default validation comes automatically from the constraints on<br />

data in the database, but you may want to modify this behavior. For example, you could limit the number of<br />

characters for a product name with the following two classes:<br />

using System.ComponentModel.DataAnnotations;<br />

namespace PCSMVCMagicShop.Models<br />

{<br />

[MetadataType(typeof(ProductMetadata))]<br />

public partial class Product<br />

{<br />

}<br />

}<br />

code snippet PCSMVCMagicShop/Models/Product.cs<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!