15.02.2015 Views

C# 4 and .NET 4

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

MVC ❘ 1273<br />

using System.ComponentModel.DataAnnotations;<br />

namespace PCSMVCMagicShop.Models<br />

{<br />

public class ProductMetadata<br />

{<br />

[StringLength(20)]<br />

public object Name { get; set; }<br />

}<br />

}<br />

This will validate the data, as shown in<br />

Figure 42-16.<br />

Obviously the code you need to use in the<br />

controller comes down to the model you are using,<br />

<strong>and</strong> this option may not always be available, but it<br />

can be very useful in the right circumstances.<br />

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

You will also probably want to edit the view<br />

figure 42-16<br />

created to provide more meaningful text, but the<br />

skeleton created is suitable for most needs. In this example, you’d probably want to change the form’s title<br />

<strong>and</strong> validation messages, as well as providing a bit more space for the item description.<br />

editing items with edit()<br />

Editing items uses very similar code to creating new items. Rather than working through how to do this,<br />

let’s just take a look at the code in the controller:<br />

public ActionResult Edit(int id)<br />

{<br />

var productToEdit = (from p in entities.Products<br />

where p.ProductId == id<br />

select p).First();<br />

}<br />

return View(productToEdit);<br />

[AcceptVerbs(HttpVerbs.Post)]<br />

public ActionResult Edit(Product productToEdit)<br />

{<br />

try<br />

{<br />

var originalProduct = (from p in entities.Products<br />

where p.ProductId == productToEdit.ProductId<br />

select p).First();<br />

}<br />

if (!ModelState.IsValid)<br />

{<br />

return View(originalProduct);<br />

}<br />

entities.ApplyCurrentValues(originalProduct.EntityKey.EntitySetName,<br />

productToEdit);<br />

entities.SaveChanges();<br />

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

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!