Populating Fields and CRUD in ASP.NET MVC

In ASP.NET MVC2 (and MVC3), when you tell Visual Studio to generate you a strongly-typed view (say, an Edit view), you see generated code that looks like (MVC3/Razor example):


@using (Html.BeginForm()) {
@Html.ValidationSummary(true)

Content

@Html.HiddenFor(model => model.Id)

@Html.LabelFor(model => model.Name)
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
@Html.LabelFor(model => model.Address)
@Html.EditorFor(model => model.Address)
@Html.ValidationMessageFor(model => model.Address)

}

You’ll notice the ubiquity of the model variable. What does this mean, and how can you populate field values?

First, you’ll notice that fields were generated for each field of our Person class, including a hidden Id field. Next, you’ll notice EditorFor (the default editor for a field), and that every field refers to model.

What this means is that, when fed the appropriate model class, the view will try to access the intended fields. So EditorFor(model => model.Address) populates the value of your model instance’s Address property into the text-box.

Effectively, this means that if you feed in the correct model instance, everything will fall into place. So how do you feed in the model instance? The answer, simply, lies in the controller. Here’s what the standard generated controller shows us for Edit:


//
// GET: /Content/Edit/5

public ActionResult Edit(int id)
{
return View();
}

You’ll notice that the View method has several overloaded signatures; one of them is View(object model). The documentation mentions that model is the model rendered by the view. Passing in the model we want, we get:


public ActionResult Edit(int id)
{
Person p = ... // use ORM
return View(p);
}

And tada! We see all the fields in our view populated with data from p. ASP.NET MVC puts two and two together, and we can see (and update) fields as expected. (Don’t forget to update the POST action of Edit to see your changes reflected and saved to the model.)

About Ashiq Alibhai, PMP

Ashiq has been coding C# since 2005. A desktop, web, and RIA application developer, he's touched ASP.NET MVC, ActiveRecord, Silverlight, NUnit, and all kinds of exciting .NET technologies. He started C# City in order to accelerate his .NET learning.
This entry was posted in Core .NET, Web and tagged , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *