Scenario is Have a GET method (Create) in which we are getting a collection into ViewBag and passing it to View to fill dropdown. Now when the ajax begin form post (Create post) happens, returning same view which requires same collection which we filled in GET (Create) method. Can we avoid this refilling of collection by any alternative way or reuse filled collection in GET method; as ultimately returning same view?
Sample code is -
// GET: Departments/Create
public ActionResult Create()
{
ViewBag.RoleId = new SelectList(db.Role, "Id", "Name");
ViewBag.UserId = new SelectList(db.User, "Id", "Name");
return PartialView();
}
// POST: Departments/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,Name,RoleId")] Department department)
{
if (ModelState.IsValid)
{
db.Department.Add(department);
db.SaveChanges();
return PartialView(department);
}
ViewBag.RoleId = new SelectList(db.Role, "Id", "Name", department.RoleId);
ViewBag.UserId = new SelectList(db.User, "Id", "Name");
return PartialView(department);
}
Aim is to avoid these two lines in post
ViewBag.RoleId = new SelectList(db.Role, "Id", "Name", department.RoleId);
ViewBag.UserId = new SelectList(db.User, "Id", "Name");
as it could add overhead in performance once the data increased.
Can you please guide on this?