You have to populate the
ViewBag
every time you show the view. The simplest option is probably to move the code to a separate method.
You'll also want to log or display the actual exception details, so that you can track down what the problem is. My guess is that there's a problem saving the file to disk.
Also remember that some browsers send the full client path of the uploaded file, rather than just the file name. You'll want to make sure you're only using the file name part.
private void PopulateLookups()
{
var categoryList = dbcontext.category.ToList();
var selectList = new List<SelectListItem>();
foreach (var item in categoryList)
{
selectList.Add(new SelectListItem { Text = item.CategoryName, Value = item.CategoryID.ToString() });
}
ViewBag.Categoryid = selectList;
}
[HttpGet]
public ActionResult Create()
{
PopulateLookups();
return View();
}
[HttpPost]
public ActionResult Create(Product product, HttpPostedFileBase file)
{
try
{
string fileName = System.IO.Path.GetFileName(file.FileName);
string physicalPath = System.IO.Path.Combine(Server.MapPath("~/Upload/"), fileName);
file.SaveAs(physicalPath);
product.Image = fileName;
dbcontext.product.Add(product);
dbcontext.SaveChanges();
return RedirectToAction("Index");
}
catch (Exception ex)
{
ViewBag.Error = ex;
PopulateLookups();
return View();
}
}
In the view:
@if (ViewBag.Error != null)
{
<p><b>Error:</b></p>
<pre>@ViewBag.Error</pre>
}