Delete Not working in MVC 2 - asp.net-mvc

// GET: /Product/Delete/5
public ActionResult Delete(int id)
{
var res = (from r in data.Products where r.ProductID == id select r).FirstOrDefault();
//return View(data.Products.FirstOrDefault(p => p.ProductID == id));
return View(res);
}
//
// POST: /Product/Delete/5
// [HttpPost]
[AcceptVerbs(HttpVerbs.Post)]
**public ActionResult Delete(Product producttodelete)**
{
try
{
// TODO: Add delete logic here
var res = (from r in data.Products where r.ProductID == producttodelete.ProductID select r).FirstOrDefault();
// var productto = data.Products.Single(p => p.ProductID == producttodelete.ProductID);
data.Products.DeleteObject(res);
data.SaveChanges();
return RedirectToAction("Index");
}
catch
{
return View();
}
}
}
Here in the line "producttodelete" i am not getting any values it is cuming null.Rather than create,details,edit are working fine.... only delete not working.......I tried a lot

Assuming you are using strongly typed views, have you tried:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Delete(int id, Product productToDelete)
{
try
{
var res = (from r in data.Products where r.ProductID == id select r).FirstOrDefault();
data.Products.DeleteObject(res);
data.SaveChanges();
return RedirectToAction("Index");
}
catch
{
return View();
}
}
... or if you are not using strongly typed views:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Delete(int id, FormCollection collection)
{
try
{
var res = (from r in data.Products where r.ProductID == id select r).FirstOrDefault();
data.Products.DeleteObject(res);
data.SaveChanges();
return RedirectToAction("Index");
}
catch
{
return View();
}
}
In either case, you need to provide an id parameter which you can then use to get your object from your datastore. The default route mapping in MVC2 (in Global.asax.cs) will take the ID from the post URL and map it to this parameter for you.

why not just get the id like you were in the rest instead of trying to get the whole model? it seems like you're just selecting using the id anyway. try this:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Delete(int id)
{
try
{
// TODO: Add delete logic here
var res = (from r in data.Products where r.ProductID == id select r).FirstOrDefault();
// var productto = data.Products.Single(p => p.ProductID == producttodelete.ProductID);
data.Products.DeleteObject(res);
data.SaveChanges();
return RedirectToAction("Index");
}
catch
{
return View();
}
}

Related

Can't get action result to run if statement and go to logged in section

For some reason, The users in db.users.Where()is not working like the rest of the users in the code. Need some assistance to make it get to the logged in stage.
public ActionResult Login()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Login(User users)
{
if (ModelState.IsValid)
{
using(DataContext db = new DataContext())
{
var obj = db.users.Where(u => u.Username.Equals(users.Username) && u.Password.Equals(users.Password)).FirstOrDefault();
if (obj != null)
{
Session["UserID"] = obj.UserID.ToString();
Session["Username"] = obj.Username.ToString();
return RedirectToAction("LoggedIn");
}
}
}
return View(users);
}
public ActionResult LoggedIn()
{
if (Session["UserID"] != null)
{
return View();
}
else
{
return RedirectToAction("Login");
}
}

Edit is Adding database record - not updating the record

I had this code working - then I added the ability to add or update an image from the edit function - not when I add an image and try to update the sql record - it adds a new record. Here is the controller code for the edit. ANy ideas?
public ActionResult Edit(int id)
{
var Emp = db.Employees.Find(id);
if (Emp == null)
{
return HttpNotFound();
}
return View(Emp);
}
// POST: Employees/Edit/5
[HttpPost]
public ActionResult Edit(int id, Employee employee, HttpPostedFileBase image1)
{
try
{
if (image1 != null)
{
employee.Image = new byte[image1.ContentLength];
image1.InputStream.Read(employee.Image, 0, image1.ContentLength);
}
db.Entry(employee).State = System.Data.Entity.EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Details", new { id = id });
}
catch
{
return View();
}
}

Mvc5 Error Please :( [duplicate]

This question already has answers here:
The ViewData item that has the key 'XXX' is of type 'System.Int32' but must be of type 'IEnumerable<SelectListItem>'
(6 answers)
Closed 5 years ago.
Hello Everybody Good day My English is not very good Poo Do not Look Mvc 5 New Start My Blog Site.
I got the error
I List Categories, I Provide Entrance to Other Areas
When I Select Photo When I Select Time
I uploaded the picture and I share the link. I am taking this mistake. Could you show me the way to this error? Thank you for your time
namespace MvcSite.Controllers
{
public class AdminMakaleController : Controller
{
MvcblogDb db = new MvcblogDb();
// GET: AdminMakale
public ActionResult Index()
{
var makale = db.Makale.ToList();
return View(makale);
}
// GET: AdminMakale/Details/5
public ActionResult Details(int id)
{
return View();
}
// GET: AdminMakale/Create
public ActionResult Create()
{
ViewBag.KategoriId = new SelectList(db.Kategori, "KategoriId", "KategoriAdi");
return View();
}
// POST: AdminMakale/Create
[HttpPost]
public ActionResult Create(Makale makale, string Etiket, HttpPostedFile Foto)
{
if (ModelState.IsValid)
{
if (Foto != null)
{
WebImage img = new WebImage(Foto.InputStream);
FileInfo fotoinfo = new FileInfo(Foto.FileName);
string newfoto = Guid.NewGuid().ToString() + fotoinfo.Extension;
img.Resize(800, 350);
img.Save("~/Uploads/MakaleFoto/" + newfoto);
makale.Foto = "/Uploads/MakaleFoto/" + newfoto;
}
if (Etiket != null)
{
string[] etiketdizi = Etiket.Split(',');
foreach (var i in etiketdizi)
{
var yenietiket = new Etiket { EtiketAdi = i };
db.Etiket.Add(yenietiket);
makale.Etiket.Add(yenietiket);
}
}
db.Makale.Add(makale);
db.SaveChanges();
return RedirectToAction("Index");
}
return View();
}
// GET: AdminMakale/Edit/5
public ActionResult Edit(int id)
{
var makales = db.Makale.Where(m => m.MakaleId == id).SingleOrDefault();
if (makales == null)
{
return HttpNotFound();
}
ViewBag.KategoriId = new SelectList(db.Kategori, "KategoriId", "KategoriAdi", makales.KategoriId);
return View(makales);
}
// POST: AdminMakale/Edit/5
[HttpPost]
public ActionResult Edit(int id, HttpPostedFile Foto, Makale makale)
{
try
{
var makales = db.Makale.Where(m => m.MakaleId == id).SingleOrDefault();
if (Foto != null)
{
if (System.IO.File.Exists(Server.MapPath(makales.Foto)))
{
System.IO.File.Delete(Server.MapPath(makales.Foto));
}
WebImage img = new WebImage(Foto.InputStream);
FileInfo fotoinfo = new FileInfo(Foto.FileName);
string newfoto = Guid.NewGuid().ToString() + fotoinfo.Extension;
img.Resize(800, 350);
img.Save("~/Uploads/MakaleFoto/" + newfoto);
makale.Foto = "/Uploads/MakaleFOTO/" + newfoto;
makales.Baslik = makale.Baslik;
makales.İcerik = makale.İcerik;
makales.KategoriId = makale.KategoriId;
db.SaveChanges();
}
return RedirectToAction("Index");
}
catch
{
ViewBag.KategoriId = new SelectList(db.Kategori, "KategoriId", "KategoriAdi", makale.KategoriId);
return View(makale);
}
}
// GET: AdminMakale/Delete/5
public ActionResult Delete(int id)
{
var makale = db.Makale.Where(m => m.MakaleId == id).SingleOrDefault();
if (makale == null)
{
return HttpNotFound();
}
return View(makale);
}
// POST: AdminMakale/Delete/5
[HttpPost]
public ActionResult Delete(int id, FormCollection collection)
{
try
{
var makales = db.Makale.Where(m => m.MakaleId == id).SingleOrDefault();
if (makales == null)
{
return HttpNotFound();
}
if (System.IO.File.Exists(Server.MapPath(makales.Foto)))
{
System.IO.File.Delete(Server.MapPath(makales.Foto));
}
foreach (var i in makales.Yorum.ToList())
{
db.Yorum.Remove(i);
}
foreach (var i in makales.Etiket.ToList())
{
db.Etiket.Remove(i);
}
db.Makale.Remove(makales);
db.SaveChanges();
return RedirectToAction("Index");
}
catch
{
return View();
}
}
}
}
Try to use a DropDownListFor instead of a DropdownList. The error you mention means that you are having NULL in the SelectListItem. You should create a list of ListItem in the DropDownList.
(I'm not sure if I'm correct or not. I'm just trying to help quickly.)

passing data(Id) with redircetToAction to url using ViewModel

hello I'm trying to pass the new posted value to a different view with the new value id at the url using RedirectToAction but I'm getting the wrong Url .
Just like here in SO ,that you get redirect to your Q. after submit.
the Url I'm suppose to get is http://localhost:1914/en/evntes/index/60
MyCode(Controler= VoosUp)
public ActionResult Create()
{
var viewModel = new LectureFormViewModel
{
Genres = _context.Genres.ToList(),
};
return View("Gigform", viewModel);
}
[Authorize, HttpPost]
public ActionResult Create(LectureFormViewModel viewModel)
{
if (!ModelState.IsValid)
{
viewModel.Genres = _context.Genres.ToList();
return View("Gigform", viewModel);
}
var lectureGig = new LectureGig
{
//Prametrest
};
_context.LectureGigs.Add(lectureGig);
_context.SaveChanges();
// return this.RedirectToAction( "events", (c=>c.Index(lectureGig.Id)); //Compiler Error
return RedirectToAction("index", "Events", new { id = lectureGig.Id });//Ok Id 60
}
Events/Index
public ActionResult Index(int id)//OK id=60
{
var lecturegig = _context.LectureGigs.Include(g => g.Artist)
.Include(g => g.Genre)
.SingleOrDefault(g => g.Id == id);
if (lecturegig == null)
return HttpNotFound();
var viewmodel = new GigDetailViewModel { LectureGig = lecturegig };
return View("index", viewmodel);
}
Url i'm getting :http://localhost:1914/en/VoosUp/Create
and the view is correct

Delete Method based on condition in MVC 4

I have created an application in MVC 4 using Razor HTML. I have set up a model that has a few properties and my delete method which is posted below. This method works perfectly except for the fact that I don't want it to allow me to delete anything if one of the properties is not a certain number. How can i implement that in this method?
public ActionResult Delete(int id = 0)
{
Material material = db.Materials.Find(id);
if(material == null)
{
return HttpNotFound();
}
return View(material);
}
[HttpPost, ActionName("Delete")]
public ActionResult DeleteConfirmed(int id)
{
Material material = db.Materials.Find(id);
db.Materials.Remove(material);
db.SaveChanges();
return RedirecttoAction("Index");
}
In both your get and post actions, check the property and return an alternate "no delete allowed" view if the property you are checking doesn't have an allowable value.
public ActionResult Delete(int id = 0)
{
Material material = db.Materials.Find(id);
if(material == null)
{
return HttpNotFound();
}
else if (material.CheckedProperty != AllowableValue)
{
return View("DeleteNotAllowed", material);
}
return View(material);
}
[HttpPost, ActionName("Delete")]
public ActionResult DeleteConfirmed(int id)
{
Material material = db.Materials.Find(id);
if (material.CheckedProperty != AllowableValue)
{
return View("DeleteNotAllowed", material);
}
db.Materials.Remove(material);
db.SaveChanges();
return RedirecttoAction("Index");
}

Resources