29.05.2015 Views

o_19mgorv9t13a3ko71fev19l81mqa.pdf

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

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

using System.Web.Mvc;<br />

using MvcModels.Models;<br />

namespace MvcModels.Controllers {<br />

public class HomeController : Controller {<br />

// ... other methods and statements omitted for brevity ...<br />

}<br />

}<br />

public ActionResult Names(string[] names) {<br />

names = names ?? new string[0];<br />

return View(names);<br />

}<br />

The Names action method takes a string array parameter called names. The model binder will look for any data item<br />

that is called names and create an array that contains those values.<br />

Tip Notice that I have to check to see if the parameter is null in the action method for this example. You can only use<br />

constant or literal values as defaults for parameters.<br />

In Listing 24-22, you can see the /Views/Home/Names.cshtml view file, which I created to show array binding.<br />

Listing 24-22. The Contents of the Names.cshtml File<br />

@model string[]<br />

@{<br />

ViewBag.Title = "Names";<br />

Layout = "∼/Views/Shared/_Layout.cshtml";<br />

}<br />

Names<br />

@if (Model.Length == 0) {<br />

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

for (int i = 0; i < 3; i++) {<br />

@(i + 1):@Html.TextBox("names")<br />

}<br />

Submit<br />

}<br />

} else {<br />

foreach (string str in Model) {<br />

@str<br />

}<br />

@Html.ActionLink("Back", "Names");<br />

}<br />

This view displays different content based on the number of items there are in the view model. If there are no items, then I<br />

display a form that contains three identical input elements, like this:<br />

...<br />

<br />

1:<br />

2:<br />

3:<br />

648

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

Saved successfully!

Ooh no, something went wrong!