Good morning, I'm learning MVC using the music store examples on the www.asp.net/mvc page, and I am having a problem with my edit action adding a new entry into the database instead of updating the existing entry. Here is my Edit action and the HTTPPost Edit.
//
// GET: /HomeScroller/Edit/5
public ActionResult Edit(int id)
{
var viewModel = new HomeScrollerViewModel()
{
ScrollerLink = dataContext.ScrollerLinks.Single(s => s.SlideID == id)
};
return View(viewModel);
}
//
// POST: /HomeScroller/Edit/5
[HttpPost]
public ActionResult Edit(int id, FormCollection formValues)
{
var scrollerLink = dataContext.ScrollerLinks.Single(s => s.SlideID == id);
try
{
UpdateModel(scrollerLink, "ScrollerLink");
dataContext.SubmitChanges();
return RedirectToAction("Index");
}
catch(Exception ex)
{
var viewModel = new HomeScrollerViewModel()
{
ScrollerLink = scrollerLink,
HasError = true,
ErrorMessage = ex.Message
};
return View(viewModel);
}
}
To give a little more background on what I am doing, I have a shared template for my Edit/Create views, and on that shared template I have a jQuery popup with a form for uploading an image. This "HomeScroller" plays a slideshow on the homepage, and I've made a back end for the admin to come in and create new slides, edit, and delete them. The other issue I am having is that when I upload an image using that second form, the main form is cleared on the post back. How do I maintain the data in those fields? Thanks.
EDIT: Here is the code for my update action
[HttpPost]
public ActionResult Upload(HttpPostedFileBase file, FormCollection formValues)
{
HomeScrollerViewModel viewModel;
Regex imageFilenameRegex = new Regex(@"(.*?)\.(jpg|jpeg|png|gif)$");
if (file.ContentLength > 0)
{
if (!imageFilenameRegex.IsMatch(file.FileName))
{
viewModel = new HomeScrollerViewModel()
{
ScrollerLink = new ScrollerLink(),
HasError = true,
ErrorMessage = "Image must be .jpg, .jpeg, .png, or .gif"
};
}
else
{
string filePath = Path.Combine(HttpContext.Server.MapPath("../Uploads"), Path.GetFileName(file.FileName));
file.SaveAs(filePath);
viewModel = new HomeScrollerViewModel()
{
ScrollerLink = new ScrollerLink()
{
ImageUrl = "../Uploads/" + file.FileName
}
};
return View("Create", viewModel);
}
}
else
{
viewModel = new HomeScrollerViewModel()
{
//ScrollerLink = scrollerLink,
HasError = true,
ErrorMessage = "Image is empty!? Try Again"
};
}
return View("Create");
}