To send error messages to views, which one is recommended? Using ViewBag or TempData?
Controller:
namesp开发者_JAVA技巧ace MvcMusicStore.Controllers
{
public class StoreController : Controller
{
MusicStoreEntities db = new MusicStoreEntities();
public ActionResult Index()
{
var genres = db.Genres.ToList();
return View(genres);
}
public ActionResult Browse(string genre)
{
var g = db
.Genres
.Include("Albums")
.FirstOrDefault(x => x.Name == genre);
if (g == null)
{
ViewBag.ErrorMessage = string.Format("Genre: {0} does not exist.", genre);
TempData["ErrorMessage"] = string.Format("Genre: {0} does not exist.", genre);
return View("Error");
}
return View(g);
}
public ActionResult Details(int id)
{
return View();
}
}
}
View:
@model System.Web.Mvc.HandleErrorInfo
@{
ViewBag.Title = "Error";
}
<h2>
ViewBag.ErrorMessage: @ViewBag.ErrorMessage
</h2>
<h2>
TempData["ErrorMessage"]: @TempData["ErrorMessage"]
</h2>
Question:
To send data to views, which one is recommended? Using ViewBag or TempData?
Depends on what your page workflow is like. If you are using the Post-Redirect-Get pattern then you must use TempData because the ViewBag won't be available after the redirect.
Personally I only use one model per view and if I need to display errors I inject values into ModelState instead. That is what ModelState is for.
精彩评论