Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

View data from view to controller

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?

like image 586
Rod Avatar asked Mar 15 '26 02:03

Rod


2 Answers

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 } );
}
like image 119
tvanfosson Avatar answered Mar 16 '26 15:03

tvanfosson


You shouldn't want to pass an object from your view to your controller, outside of calling a controller's action. If you're trying to pass a parameter to your controller action, you can add in a route value.

For example this will pass the value 3 as the id parameter into your action (using the route logic)

@Html.ActionLink("Home", "Details", new { id = 3 });
like image 20
Ken Pespisa Avatar answered Mar 16 '26 14:03

Ken Pespisa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!