Question

I am writing a simple booking system in MVC 4. When a booking is submitted using the form I want to redirect to the next page but I want to pass my model data.

 [HttpPost]
        public ActionResult Index(CustomerBookingModel CustomerBooking)
        {

            if (ModelState.IsValid)
            {
                switch (CustomerBooking.Cancellation)
                {
                    case true:
                        //TODO: Data layer method for cancellation
                        CustomerBooking.ActionStatus = StatusCode.Cancelled.ToString();
                        break;
                    case false:
                        //TODO: Data layer method for making a booking in DB
                        CustomerBooking.ActionStatus = StatusCode.Booked.ToString();
                        break;
                }
                TempData["Model"] = CustomerBooking;
                return RedirectToAction("About");                
            }
            else
            {
                return View();
            }
        }

If my model is valid I do some logic based on the status of the booking. I then populate TempData which I want to access in ActionMethod about.

public ActionResult About()
        {
            if (TempData["Model"] != null)
            {
                var model = TempData["Model"];
                return View(model);
            }

            return View();
        }

What is a good way of displaying this data in the view?

@ViewData["Model"]
@{
    ViewBag.Title = "About";
}

My view is empty because I am using viewdata and not a model.

Was it helpful?

Solution

Since TempData will return an object you should try to cast it back.

Controller

public ActionResult About()
{
    var model = (TempData["Model"] as CustomerBookingModel)
                ?? new CustomerBookingModel();

    return View(model);
}

About.cshtml

@model CustomerBookingModel

@Html.DisplayForModel();

DisplayTemplates/CustomerBookingModel.cshtml

@model CustomerBookingModel

<div>
    @Html.LabelFor(m => m.SomeProperty)
    <p>@Model.SomeProperty</p>
</div>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top