3

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

4 Answers 4

9

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
}
0
2

The hidden field should works. The problem is that your controller did not accept it.

You can use ViewModel to achieve this. Or, use the code below in your action:

id = Request.Form["id"]
1
  • Thank you for the responses. I used Request.Form, per Robby Shaw. Mar 19, 2012 at 8:23
0

Try like this:

@using (Html.BeginForm("AddReturn", "DealerAdmin", new { id = ViewBag.Id }))
{
    ...
}
2
  • Thank you. HOw do I retrieve the value in my post action in my controller? Mar 19, 2012 at 7:54
  • You could have your controller action take a view model with an Id property. The default model binder will then automatically populate this property. Mar 19, 2012 at 7:56
0

there some way
1. send the value with query string if there is only one value to send to the controller
2. if you want collect many field from view you can use formcollection
sample::

public actionresult method1()
{
 int id = //everything you want
 viewbag.id=id;
 ....
 //and other field to collect
}

in view

<form method="post" action="method1" enctype="now i dont remeber the value of this option" >

@html.hidden("id")
.....

<input type="submit" value"Send"/>
</form>

[httpPost]
public actionresult method1(fromcollection collection)
{
 int id = collection.get("id");
 ....
 //and other field to collect
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.