I want to edit some of the attributes of the database but have the problem
This is code controller
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Product_ID,Product_Name,Product_Price,Product_Date,Product_Image," +
"Product_Description,Product_Discount,Category_ID,Supply_ID")] Product product, HttpPostedFileBase photo)
{
if (ModelState.IsValid)
{
if (photo != null)
{
if (!isValidContentType(photo.ContentType))
{
ViewBag.Error = "Error";
return View();
}
else
{
var fileName = new FileInfo(photo.FileName);
photo.SaveAs(Server.MapPath("~/Images/" + fileName));
product.Product_Image = photo.FileName;
}
}
else
return RedirectToAction("Index");
db.Entry(product).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.Category_ID = new SelectList(db.Categories, "Category_ID", "Category_Name", product.Category_ID);
ViewBag.Supply_ID = new SelectList(db.Supplies, "Supply_ID", "Supply_Name", "Supply_Address");
return View(product);
}
I want when i do not change the picture. Other attributes are still changing.
This code now, when i do not change the image and other attributes still not change.
PLease help me fixed. Thanks
Solution, try it :
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Product_ID,Product_Name,Product_Price,Product_Date,Product_Image," +
"Product_Description,Product_Discount,Category_ID,Supply_ID")] Product product, HttpPostedFileBase photo)
{
if (ModelState.IsValid)
{
if (photo != null)
{
if (!isValidContentType(photo.ContentType))
{
ViewBag.Error = "Error";
return View();
}
else
{
var fileName = new FileInfo(photo.FileName);
photo.SaveAs(Server.MapPath("~/Images/" + fileName));
product.Product_Image = photo.FileName;
}
}
db.Entry(product).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.Category_ID = new SelectList(db.Categories, "Category_ID", "Category_Name", product.Category_ID);
ViewBag.Supply_ID = new SelectList(db.Supplies, "Supply_ID", "Supply_Name", "Supply_Address");
return View(product);
}
Related
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");
}
}
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();
}
}
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.)
This my Code
Model
public class ViewModelRequestPurchaseItem
{
public List<RequestPurchase> RequestPurchases { get; set; }
public List<RequestPurchaseItem> RequestPurchaseItems { get; set; }
}
View
#using EFMySQLCardTest.Models
#model EFMySQLCardTest.Models.ViewModelRequestPurchaseItem
Controller
public ActionResult Edit([Bind(Include = "RequestPurchases,RequestPurchaseItems")] ViewModelRequestPurchaseItem viewModelRequestPurchaseItem, string id)
{
var requestPurchase = db.RequestPurchase.Where(x => x.RequestPurchaseNumber == id).ToList();
var requestPurchaseItem = db.RequestPurchaseItem.Where(x => x.RequestPurchaseNumber == id).OrderBy(x => x.RequestPurchaseItemID).ToList();
viewModelRequestPurchaseItem.RequestPurchases = requestPurchase;
viewModelRequestPurchaseItem.RequestPurchaseItems = requestPurchaseItem;
if (ModelState.IsValid)
{
db.Entry(viewModelRequestPurchaseItem).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
else
{
this.ExpendErrors();
}
return View(viewModelRequestPurchaseItem);
}
In this line:
db.Entry(viewModelRequestPurchaseItem).State = EntityState.Modified
the error is:
viewModelRequestPurchaseItem is not model of parts
ViewModelRequestPurchaseItem is your view model and is not part of the database context. You need to save each RequestPurchase and RequestPurchaseItems in the collections. You current code is also assigning the collections to the current values in the database, wiping out any edits you have made in the view. Your method should be
public ActionResult Edit(ViewModelRequestPurchaseItem model)
{
if (ModelState.IsValid)
{
return View(model);
}
foreach (RequestPurchase item in model.RequestPurchases)
{
db.Entry(item).State = EntityState.Modified;
}
// ditto for RequestPurchaseItems
db.SaveChanges();
return RedirectToAction("Index");
}
I have created a repository data layer in my MVC web application, and want to use it for my CRUD methods. But I came to think of situations where I want to do something like:
If record does not exist
create record
else
update record
But how does this fit into CRUD? Is this two-in-one operation logic supposed to be kept in the controller?
I think the repository should take care of that, the controller should be as light as possible:
At repository level:
public bool CreateUpdate(Type model)
{
var record = db.FirstOrDefault(x=> x.Id == model.Id);
if(record == null)
{
Create(model);
}
else
{
Update(model);
}
}
public bool Create(Type model)
{
//create logic here
}
public bool Update(Type model)
{
//update logic here
}
This can be done with this code
var data = db.tableName.where(x=> x.Id == model.Id).FirstOrDefault();
if(data== null)
{
db.FAQCategories.Add(model);
db.SaveChanges();
}
else
{
db.Entry(model).State = EntityState.Modified;
db.SaveChanges();
}
public IActionResult Create()
{
return View();
}
// POST: AdminPanel/Students/Create
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(Student student)
{
if (!ModelState.IsValid)
{
return View();
}
student.Image = await student.Photo.SaveFileAsync(_environment.WebRootPath, "images");
await _context.Students.AddAsync(student);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
// GET: AdminPanel/Students/Edit/5
public async Task<IActionResult> Update(int? id)
{
if (id == null)
{
return BadRequest();
}
var student = await _context.Students.FindAsync(id);
if (student == null)
{
return NotFound();
}
return View(student);
}
// POST: AdminPanel/Students/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Update(int? id, Student newstudent)
{
if (id==null)
{
return BadRequest();
}
var oldstudent = _context.Students.Find(id);
if (oldstudent == null)
{
return NotFound();
}
if (!ModelState.IsValid)
{
return View();
}
var path = Helper.GetPath(_environment.WebRootPath, "images", oldstudent.Image);
if (System.IO.File.Exists(path))
{
System.IO.File.Delete(path);
}
newstudent.Image = await newstudent.Photo.SaveFileAsync(_env.WebRootPath, "images");
oldstudent.Image = newstudent.Image;
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
public async Task<IActionResult> Delete(int id)
{
if (id == null)
{
return BadRequest();
}
var student= _context.Students.Find(id);
if (student== null)
{
return NotFound();
}
_context.Students.Remove(student);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
}
}