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.

MVC ❘ 1271<br />

<br />

<br />

<br />

<br />

<br />

<br />

<br />

<br />

<br />

code snippet PCSMVCMagicShop/Views/Products/Create.aspx<br />

Several helper methods are included here to create <strong>and</strong> edit the form, <strong>and</strong> again you can see how the data<br />

model has been interrogated to extract information for the fields to use <strong>and</strong> the validation required. The<br />

form itself is contained in the following code block:<br />

using (Html.BeginForm())<br />

{<br />

...<br />

}<br />

This helper method creates a form that is submitted using a st<strong>and</strong>ard HTML <br />

control, which results in the form values being passed to the action method. You then have access to these<br />

values so that you can add a new item.<br />

You can delete the following section of code to remove the text box for the product ID, since this is<br />

auto-generated:<br />

<br />

<br />

ProductId:<br />

<br />

<br />

<br />

The code required to add an item is as follows:<br />

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

public ActionResult Create([Bind(Exclude = "ProductId")] Product productToCreate)<br />

{<br />

try<br />

{<br />

if (!ModelState.IsValid)<br />

{<br />

return View();<br />

}<br />

}<br />

entities.AddToProducts(productToCreate);<br />

entities.SaveChanges();<br />

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

}<br />

catch<br />

{<br />

return View();<br />

}<br />

code snippet PCSMVCMagicShop/Controllers/ProductsController.cs<br />

There are several points to note about this code. First, note that you can change the method signature to<br />

accept a strongly-typed Product value. This is easier than working through a collection of form values, but to<br />

facilitate it you need to exclude the ProductId field, since it won’t be passed. The Bind attribute achieves this.<br />

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!