JT_SIRO
asked on
How do I override the db.SaveChanges method that MVC scaffolding built?
Hi,
I'm new to MVC. I built a model and let MVC do scaffolding. It works great, but I need to know how to override the @Html.EditorFor(model => model.PROPERTY) behavior...
For instance, I created a dropdown on my Edit page, like so:
Album: @Html.DropDownList("ddAlbu m", @Model.Album)
Where the MVC scaffolding had:
@Html.EditorFor(model => model.Album)
How do I save the value from my dropdownlist to save in the db.SaveChanges() method? In the following scaffolded code:
if (ModelState.IsValid)
{
db.Entry(song).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
I'm new to MVC. I built a model and let MVC do scaffolding. It works great, but I need to know how to override the @Html.EditorFor(model => model.PROPERTY) behavior...
For instance, I created a dropdown on my Edit page, like so:
Album: @Html.DropDownList("ddAlbu
Where the MVC scaffolding had:
@Html.EditorFor(model => model.Album)
How do I save the value from my dropdownlist to save in the db.SaveChanges() method? In the following scaffolded code:
if (ModelState.IsValid)
{
db.Entry(song).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
Is there a post back that calls the db.SaveChanges? Is that code in a controller action method?
ASKER
Yes, it's in the postback Edit Action of my controller. Like so:
//
// POST: /Songs/Edit/5
[HttpPost]
public ActionResult Edit(Song song)
{
// UPLOAD SONG PHOTO TO C:\SongBank\Images\
foreach (string upload in Request.Files)
{
if (!Request.Files[upload].Ha sFile()) continue;
string path = AppDomain.CurrentDomain.Ba seDirector y + "Content/SongPhotos";
string filename = Path.GetFileName(Request.F iles[uploa d].FileNam e);
Request.Files[upload].Save As(Path.Co mbine(path , filename));
}
if (ModelState.IsValid)
{
db.Entry(song).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(song);
}
//
// POST: /Songs/Edit/5
[HttpPost]
public ActionResult Edit(Song song)
{
// UPLOAD SONG PHOTO TO C:\SongBank\Images\
foreach (string upload in Request.Files)
{
if (!Request.Files[upload].Ha
string path = AppDomain.CurrentDomain.Ba
string filename = Path.GetFileName(Request.F
Request.Files[upload].Save
}
if (ModelState.IsValid)
{
db.Entry(song).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(song);
}
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Thanks!