ASP.NET MVC Redirect with model

Straight from my own app:

public ActionResult Create(Booking item)
{
    if (ModelState.IsValid)
    {
        int newID = _tasks.Create(item);
        // NEW section to emulate model being populated for use in Details view
        TempData["additionalData"] = "Person created successfully";
        return RedirectToAction("Details", new { id = newID });
    }
    else
    {
        return View();
    }
}

then, couldn’t your “Details” action be like this:

public ActionResult Details(int id)
{
    var item = _tasks.GetByKey(id);
    var additionalData = TempData["additionalData"];
    if(item != null) {
        if(additonalMessage!=null)
        {
            item.additionalData = additionalData;
        }
        return View(item);
    }
    else
        return View("Notfound");
}

couldn’t you adopt a similar approach??

You could just do the redirect as per convention and have a flag set (on tempdata as above) that gives this message? The tempadata flag would ONLY be set inside the Create action, therefore would only ever happen on Creating a new ‘person’ object. thus the Details action would only ever show it as a consequence of the Create action

Leave a Comment