Twisted
Twisted

Reputation: 45

Display FormCollection with ASP.NET MVC

I have a form using Html.BeginForm() on a view. I have in the controller an ActionResult to handle the post. What I need is to just kick back the results to a view. I can kick off the new view, but I don't know how to pass the data to it and once there I don't know how to display it. Here's what I have in the ActionResult.

[HttpPost]
        public ActionResult Index(FormCollection collection)
        {


            ViewBag.Title = "Confirm your order";
            return View("OrderConfirmation", collection);
        }

If I just do a return View("OrderConfirmation"); it will go to the view so I know I got that working. I just don't know how to pass the data. Right now I have it strongly typed to the same model the form was which causes errors because this FormCollection is not the same obviously. If I remove the strongly typed line the above works, but I have no idea how to loop through the collection at that point.

Thanks for the help.

Upvotes: 0

Views: 2149

Answers (2)

Adam Tuliper
Adam Tuliper

Reputation: 30152

First don't use FormsCollection, its too generic. You only need it if you need to unit test and access UpdateModel().

Bind to a model type or bind to params:

public ActionResult Index(SomeModel model)
{
  return View("OrderConfirmation", model);
}

or

public ActionResult Index(int key)
{
   SomeModel model = new SomeModel();
   UpdateModel(model);
  return View("OrderConfirmation", model);
}

in your view at the top specify

@model MyAppNameSpace.ViewModels.SomeModel

Upvotes: 2

slfan
slfan

Reputation: 9129

Use a ViewModel and a stongly typed view. Then you can pass the model to the second view.

public ActionResult Index(Order order)
{
  return View("OrderConfirmation", order);
}

ASP.NET MVC will automatically create an order instance and fill the properties from the posted FormCollection.

Upvotes: 2

Related Questions