ASP.NET MVC Redirect with model

蹲街弑〆低调 提交于 2019-12-03 05:15:41
jim tollan

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

This should take you to the Details Model, passing the ID with it.

return RedirectToAction("Details", new { id = person.PersonID });

You could supplement what has been offered (use RedirectToAction and routing) with the use of TempData

[HttpPost]
public virtual ActionResult Create(IEnumerable<OrderItem> orderItems)
    {
        if (orderItems.Count() == 0)
        {
            return RedirectToAction("NoOrderItems");
        }
        else
        {
            TempData["orderItems"] = orderItems;
            return RedirectToAction("Confirm");
        }
    }

    [HttpGet]
    public virtual ActionResult Confirm()
    {
        var orderItems = TempData["orderItems"] as IEnumerable<OrderItem>;
        if (orderItems == null || orderItems.Count() == 0)
        {
            this.InvokeHttp404(ControllerContext.HttpContext);
        }

        return View(orderItems);
    }

I use this for items that I might not want to create again on subsequent requests or persist quite yet in the database yet. With this, I don't need null checks in my view, as the Confirm page can only be "gotten" if there is data for it.

Mind you could also take the type-safe approach of MvcContrib and do

return this.RedirectToAction<MyController>(c => c.Details(person.PersonID));
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!