Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC3 Razor - How to pass data from controller to view - and back to controller

I have a view where everything will be populated by the user - but relates to a parent entity. I pass that Id to my view using ViewBag, but I don't know how to get it back to the post action in the controller. I have tried hidden form fields, but it isn't showing in the post, or I do not know how to grab it... Controller:

public ActionResult AddCar(int id)
{
ViewBag.Id = id;
return View();
}

View (tried):

    @using (Html.BeginForm("AddReturn", "DealerAdmin", new { id = carId }))
    {
View (tried):
     @Html.Hidden(carId.ToString())

HOw do I retrieve the value in my post action in my controller? Or is there a better/different way to approach it? THanks

like image 991
user1166147 Avatar asked Jan 27 '26 18:01

user1166147


1 Answers

Create a ViewModel for post, it would be as follows

public class Post
{
   int id {get;set;}
   //other properties
}

and in your controller action send a post object

public ActionResult AddCar(int id)
{
 Post post = new Post();
 post.Id = id;
return View(post);
}

your view should use the Post class as the model

@model namespace.Post
@using (Html.BeginForm("AddReturn", "DealerAdmin", FormMethod.Post)
    {
      @Html.HiddenFor(model => model.Id)
    }

and your controller action which expects result should have a post object as the input parameter

public ActionResult AddReturn(Post post)
{
 //your code
}
like image 80
Jayanga Avatar answered Jan 30 '26 16:01

Jayanga



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!