View data from view to controller

Rod picture Rod · May 13, 2011 · Viewed 10.2k times · Source

Is there an easy way to pass an object from my view to controller?

I tried ViewData["newPerson"] but that didn't work.

Session["newPerson"] works but are there other ways that are more recommended?

Answer

tvanfosson picture tvanfosson · May 13, 2011

Usually you'd receive a model as the parameter. You'd have to have form fields that map to the model's properties.

public class PersonViewModel
{
     [Required]
     public string FirstName { get; set; }

     [Required]
     public string LastName { get; set; }
     ...
}

Then in your view:

@model PersonViewModel
@using (Html.BeginForm())
{
      <div class="editor-label">@Html.LabelFor( model => model.FirstName )</div>
      <div class="editor-field">@Html.EditorFor( model => model.FirstName )</div>

      <div class="editor-label">@Html.LabelFor( model => model.LastName )</div>
      <div class="editor-field">@Html.EditorFor( model => model.LastName )</div>
      ...
}

Then in the actions corresponding to the view send and receive the model

[HttpGet]
public ActionResult CreatePerson()
{
     return View( new Person() );
}

[HttpPost]
public ActionResult CreatePerson( PersonViewModel person )
{
    var person = ...create and persist a Person entity based on the view model....
    return Redirect("details", new { id = person.id } );
}