My delete method is not working, here is what is happening at the moment. Using EF I created a CRUD to interact with an existing DB. Right now I have the Edit method working fine as well as the index list but the Delete method is still giving me problems. When I go to the delete button for a specific record it brings up the delete view for that record and asks if I am sure I want to delete the record. I then hit submit and the data disappears from the view but does not redirect me to the index page like it should be doing. When I hit back to list it takes me back to the index view but the record is still in the table. It seems strange to me that the data disappears from the view but not the DB.
From what I can tell from other examples I have seen my code looks correct but it can't be because it's not working! I'm unsure of where this error could be coming from so below I have posted my code for my controller, Delete class, and index class.
PACONTROLLLER
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DBFirstMVC.Models;
using System.Data;
namespace DBFirstMVC.Controllers
{
public class PaController : Controller
{
PaEntities db = new PaEntities();
//
// GET: /Pa/
public ActionResult Index()
{
using (var db = new PaEntities())
{
return View(db.iamp_mapping.ToList());
}
}
//
// GET: /Pa/Details/5
public ActionResult Details(int id)
{
return View();
}
//
// GET: /Pa/Create
public ActionResult Create()
{
return View();
}
//
// POST: /Pa/Create
[HttpPost]
public ActionResult Create(iamp_mapping IAMP)
{
try
{
using (var db = new PaEntities())
{
db.iamp_mapping.Add(IAMP);
db.SaveChanges();
}
return RedirectToAction("Index");
}
catch
{
return View();
}
}
//
// GET: /Pa/Edit/5
public ActionResult Edit(string id)
{
using (var db = new PaEntities())
{
return View(db.iamp_mapping.Find(id));
}
}
//
// POST: /Pa/Edit/5
[HttpPost]
public ActionResult Edit(string id, iamp_mapping IAMP)
{
try
{
using (var db = new PaEntities())
{
db.Entry(IAMP).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Pa");
}
}
catch
{
return View();
}
}
//
// GET: /Pa/Delete/5
public ActionResult Delete(string id)
{
using (var db = new PaEntities())
{
return View(db.iamp_mapping.Find(id));
}
}
//
// POST: /Pa/Delete/5
[HttpPost]
public ActionResult Delete(string id, iamp_mapping IAMP)
{
try
{
using (var db = new PaEntities())
{
db.Entry(IAMP).State = EntityState.Deleted;
db.SaveChanges();
return RedirectToAction("Pa");
}
}
catch
{
return View();
}
}
}
}
DELETE CLASS
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DBFirstMVC.Models;
using System.Data;
namespace DBFirstMVC.Controllers
{
public class PaController : Controller
{
PaEntities db = new PaEntities();
//
// GET: /Pa/
public ActionResult Index()
{
using (var db = new PaEntities())
{
return View(db.iamp_mapping.ToList());
}
}
//
// GET: /Pa/Details/5
public ActionResult Details(int id)
{
return View();
}
//
// GET: /Pa/Create
public ActionResult Create()
{
return View();
}
//
// POST: /Pa/Create
[HttpPost]
public ActionResult Create(iamp_mapping IAMP)
{
try
{
using (var db = new PaEntities())
{
db.iamp_mapping.Add(IAMP);
db.SaveChanges();
}
return RedirectToAction("Index");
}
catch
{
return View();
}
}
//
// GET: /Pa/Edit/5
public ActionResult Edit(string id)
{
using (var db = new PaEntities())
{
return View(db.iamp_mapping.Find(id));
}
}
//
// POST: /Pa/Edit/5
[HttpPost]
public ActionResult Edit(string id, iamp_mapping IAMP)
{
try
{
using (var db = new PaEntities())
{
db.Entry(IAMP).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Pa");
}
}
catch
{
return View();
}
}
//
// GET: /Pa/Delete/5
public ActionResult Delete(string id)
{
using (var db = new PaEntities())
{
return View(db.iamp_mapping.Find(id));
}
}
//
// POST: /Pa/Delete/5
[HttpPost]
public ActionResult Delete(string id, iamp_mapping IAMP)
{
try
{
using (var db = new PaEntities())
{
db.Entry(IAMP).State = EntityState.Deleted;
db.SaveChanges();
return RedirectToAction("Pa");
}
}
catch
{
return View();
}
}
}
}
INDEX Class
#model IEnumerable<DBFirstMVC.Models.iamp_mapping>
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table>
<tr>
<th>
PA
</th>
<th>
MAJOR PROGRAM
</th>
<th>
INVESTMENT AREA
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.PA)
</td>
<td>
#Html.DisplayFor(modelItem => item.MAJOR_PROGRAM)
</td>
<td>
#Html.DisplayFor(modelItem => item.INVESTMENT_AREA)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id=item.PA }) |
#Html.ActionLink("Delete", "Delete", new { id=item.PA })
</td>
</tr>
}
</table>
So I figured out my own question even though at this time 27 people have viewed my question at this time without even a comment(not bitter just sayin'). The reason that this is happening is after you delete a row the primary key gets deleted and returns a null value. Primary keys cannot have null values so this was causing my code to throw an error here.
[HttpPost]
public ActionResult Delete(string id, iamp_mapping IAMP)
{
try
{
using (var db = new PaEntities())
{
db.Entry(IAMP).State = EntityState.Deleted; <---------
db.SaveChanges();
return RedirectToAction("Index");
}
}
catch (Exception e)
{
throw (e);
//return View();
}
}
I fixed this by changing the primary key variable the program uses to bring up the id like this.
[HttpPost]
public ActionResult Delete(string id, iamp_mapping IAMP)
{
try
{
using (var db = new PaEntities())
{
var vIAMP = db.iamp_mapping.Find(id); <---------------
db.Entry(vIAMP).State = EntityState.Deleted;
db.SaveChanges();
return RedirectToAction("Index");
}
}
catch (Exception e)
{
throw (e);
//return View();
}
}
Related
I am still fairly new to ASP.NET Core and I am not 100% sure on what I am doing, but I have hobbled together a recipe keeper program, but I am having issues displaying the images.
When I run the program, the view shows that it is getting the image file name and the dev tools shows the correct src code, but the image is still not showing up. I have the code set to show a generic "no image" image when the view can't find the image assigned to the particular recipe but that shouldn't be the case.
I originally had this part working and I'm not sure why it is not anymore. I have tried to retrace my steps from when I noticed the issue, but it has been several days since I completed the image part of this program, so I am not sure where the issue is.
View showing image is there
Page showing generic image
DevTools showing the src
RecipeController:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using WhatsForDinner.Data;
using WhatsForDinner.Models;
namespace WhatsForDinner.Controllers
{
public class RecipesController : Controller
{
private readonly ApplicationDbContext _context;
private readonly IWebHostEnvironment webHostEnvironment;
public RecipesController(ApplicationDbContext context, IWebHostEnvironment webHostEnvironment)
{
_context = context;
this.webHostEnvironment = webHostEnvironment;
}
// GET: Recipes
public async Task<IActionResult> Index()
{
var applicationDbContext = _context.Recipes
.Include(r => r.ApplicationUser)
.Where(a => a.ApplicationUser.Id == HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value);
return View(await applicationDbContext.ToListAsync());
}
// GET: Recipes/Details/5
public async Task<IActionResult> Details(int? id)
{
if (id == null || _context.Recipes == null)
{
return NotFound();
}
var recipe = await _context.Recipes
.Include(r => r.ApplicationUser)
.FirstOrDefaultAsync(m => m.RecipeId == id);
if (recipe == null)
{
return NotFound();
}
return View(recipe);
}
// GET: Recipes/Create
public IActionResult Create()
{
//ViewData["ApplicationUserId"] = new SelectList(_context.User, "Id", "Id");
//ViewBag.ApplicationUserId = HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value;
return View();
}
// POST: Recipes/Create
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("RecipeId, UploadDateAndTime, RecipeTitle, RecipeDescription, PrepTime, NumOfServings, ServingSize, Ingredients, Directions, Notes, RecipePhoto, ApplicationUserId, RecipePhoto")] Recipe recipe, IFormFile file)
{
if (ModelState.IsValid)
{
string uniqueFileName = null;
if (file != null)
{
string uploadsFolder = Path.Combine(webHostEnvironment.WebRootPath, "Images");
uniqueFileName = file.FileName;
string filePath = Path.Combine(uploadsFolder, uniqueFileName);
using (var fileStream = new FileStream(filePath, FileMode.Create))
{
file.CopyTo(fileStream);
}
}
recipe.RecipePhoto = uniqueFileName;
recipe.ApplicationUserId = HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value;
_context.Add(recipe);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
// ViewData["ApplicationUserId"] = new SelectList(_context.User, "Id", "Id", recipe.ApplicationUserId);
// ViewBag.ApplicationUserId = HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value;
return View(recipe);
}
// GET: Recipes/Edit/5
public async Task<IActionResult> Edit(int? id)
{
if (id == null || _context.Recipes == null)
{
return NotFound();
}
var recipe = await _context.Recipes.FindAsync(id);
if (recipe == null)
{
return NotFound();
}
// ViewData["ApplicationUserId"] = new SelectList(_context.User, "Id", "Id", recipe.ApplicationUserId);
// ViewBag.ApplicationUserId = HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value;
return View(recipe);
}
// POST: Recipes/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, [Bind("RecipeId, UploadDateAndTime, RecipeTitle, RecipeDescription, PrepTime, NumOfServings, ServingSize, Ingredients, Directions, Notes, ApplicationUserId")] Recipe recipe)
{
if (id != recipe.RecipeId)
{
return NotFound();
}
if (ModelState.IsValid)
{
try
{
recipe.ApplicationUserId = HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value;
_context.Update(recipe);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!RecipeExists(recipe.RecipeId))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction(nameof(Index));
}
// ViewData["ApplicationUserId"] = new SelectList(_context.User, "Id", "Id", recipe.ApplicationUserId);
// ViewBag.ApplicationUserId = HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value;
return View(recipe);
}
// GET: Recipes/Delete/5
public async Task<IActionResult> Delete(int? id)
{
if (id == null || _context.Recipes == null)
{
return NotFound();
}
var recipe = await _context.Recipes
.Include(r => r.ApplicationUser)
.FirstOrDefaultAsync(m => m.RecipeId == id);
if (recipe == null)
{
return NotFound();
}
return View(recipe);
}
// POST: Recipes/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int id)
{
if (_context.Recipes == null)
{
return Problem("Entity set 'ApplicationDbContext.Recipes' is null.");
}
var recipe = await _context.Recipes.FindAsync(id);
if (recipe != null)
{
_context.Recipes.Remove(recipe);
}
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
private bool RecipeExists(int id)
{
return _context.Recipes.Any(e => e.RecipeId == id);
}
}
}
I am not sure why the images are not showing anymore. Any thoughts?
I am not sure why the images are not showing anymore. Any thoughts?
Well, your issue is pretty obvious, as you are using type="image/*" to display image. However, this is not the correct way to do that. I have reproduced your issue thus have a look the solution as well.
Solution:
You should use accept="image/*"> instead of type="image/*". This the reason your image has not displayed. Your full code should be as following:
<td>
<object class="card-img-top" height="50" width="75" data="~/Image/#Html.DisplayFor(modelItem=>item.RecipePhoto)" accept="image/*">
</object>
</td>
Another way:
<td>
<object class="card-img-top" height="50" width="75" data="~/ImageName/Cover/#item.RecipePhoto" accept="image/*">
</object>
</td>
Output:
I have dropdownlst which i have filled from database. Now i need to get the selected value in Controller do some manipulation. But null data will get. Code which i have tried.
##View##
#using (Html.BeginForm()) {
#Html.DropDownList("SupplierId", ViewBag.PurSupName as SelectList, new {#class = "form-control",style = "width: 200px;",id="supId"})
}
## Controller ##
public ActionResult ItemPurchased()
{
POS_DBEntities2 db = new POS_DBEntities2();
var query = from i in db.TBL_Account
where i.Type == "supplier"
select i;
ViewBag.PurSupName = new SelectList(query, "AccountId", "AccountName");
return PartialView("ItemPurchased", new List<PurchasedItem>());
}
##Controller##
public ActionResult GetPurchasedItem()
{
var optionsValue = this.Request.Form.Get("SupplierId");
return View();
}
You can try with below changes.
#using (Html.BeginForm("GetPurchasedItem","YourController")) {
#Html.DropDownList("SupplierId", ViewBag.PurSupName as SelectList, new {#class = "form-control",style = "width: 200px;",id="supId"})
<input type="submit" value="OK" />
}
Controller will be
[HttpPost]
public ActionResult GetPurchasedItem(string SupplierId)
{
var optionsValue = SupplierId;
//..............
return View();
}
It should work normally..
I am doing a ASP.NET MVC tutorial. I created a Dinner Controller as well as a index view of Dinner Controller. But, I got an error on my Dinner Index View. The error appears on the for each loop in the following code. But the dinner index view is generated by default. I didnt change any thing.
The code of my Dinner Index View is
#model IEnumerable<NerdDinner.Models.Dinner>
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table>
<tr>
<th>
Title
</th>
<th>
Latitude
</th>
<th>
Longitude
</th>
<th>
EventDate
</th>
<th>
ContactPhone
</th>
<th>
Address
</th>
<th>
Country
</th>
<th>
HostedBy
</th>
<th>
Description
</th>
<th></th>
</tr>
#foreach (var item in Model) {//Error appears here
<tr>
<td>
#Html.DisplayFor(modelItem => item.Title)
</td>
<td>
#Html.DisplayFor(modelItem => item.Latitude)
</td>
<td>
#Html.DisplayFor(modelItem => item.Longitude)
</td>
<td>
#Html.DisplayFor(modelItem => item.EventDate)
</td>
<td>
#Html.DisplayFor(modelItem => item.ContactPhone)
</td>
<td>
#Html.DisplayFor(modelItem => item.Address)
</td>
<td>
#Html.DisplayFor(modelItem => item.Country)
</td>
<td>
#Html.DisplayFor(modelItem => item.HostedBy)
</td>
<td>
#Html.DisplayFor(modelItem => item.Description)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id=item.DinnerID }) |
#Html.ActionLink("Details", "Details", new { id=item.DinnerID }) |
#Html.ActionLink("Delete", "Delete", new { id=item.DinnerID })
</td>
</tr>
}
</table>
The code of my Dinner controller is
namespace NerdDinner.Controllers
{
public class DinnerController : Controller
{
IDinnerRepository _repository;
public DinnerController()
{
_repository = new sqlDinnerRepository();
}
public DinnerController(IDinnerRepository repository)
{
_repository = repository;
}
//
// GET: /Dinner/
public ActionResult Index()
{
if (Request.IsAjaxRequest())
{
var dinners = _repository.FindAllDinners().Where(x => x.EventDate >= DateTime.Now).ToList();
return Json(dinners);
}
else
{
return View();
}
}
//
// GET: /Dinner/Details/5
public ActionResult Details(int id)
{
var dinner = _repository.GetDinner(id);
return View(dinner);
}
//
// GET: /Dinner/Create
public ActionResult Create()
{
return View();
}
//
// POST: /Dinner/Create
[HttpPost]
public ActionResult Create(Dinner dinner)
{
try
{
// TODO: Add insert logic here
_repository.AddDinner(dinner);
_repository.Save();
return RedirectToAction("Index");
}
catch
{
return View(dinner);
}
}
//
// GET: /Dinner/Edit/5
public ActionResult Edit(int id)
{
var dinner = _repository.GetDinner(id);
return View(dinner);
}
//
// POST: /Dinner/Edit/5
[HttpPost]
public ActionResult Edit(int id, FormCollection collection)
{
var dinner = _repository.GetDinner(id);
try
{
// TODO: Add update logic here
UpdateModel(dinner, collection.ToValueProvider());
_repository.Save();
return RedirectToAction("Index");
}
catch
{
return View(dinner);
}
}
//
// POST: /Dinner/Delete/5
[HttpPost]
public ActionResult Delete(int id)
{
var dinner = _repository.GetDinner(id);
try
{
// TODO: Add delete logic here
_repository.DeleteDinner(dinner);
_repository.Save();
return RedirectToAction("Index");
}
catch
{
return View(dinner);
}
}
}
}
IDinnerRepository is an interface and sqlDinnerRepository implements it
The code of IDinnerRepository is
namespace NerdDinner.Models
{
public interface IDinnerRepository
{
//Query Methods
IQueryable<Dinner> FindAllDinners();
IQueryable<Dinner> FindUpcomingDinners();
Dinner GetDinner(int id);
//Insert/Delete
void AddDinner(Dinner dinner);
void DeleteDinner(Dinner dinner);
//Persistence
void Save();
}
}
The code of sqlDinnerRepository is
namespace NerdDinner.Models
{
public class sqlDinnerRepository: IDinnerRepository
{
public dbDataContext db;
public sqlDinnerRepository()
{
db = new dbDataContext();
}
public IQueryable<Dinner> FindAllDinners()
{
return db.Dinners;
}
public IQueryable<Dinner> FindUpcomingDinners()
{
return from dinner in db.Dinners
where dinner.EventDate > DateTime.Now
orderby dinner.EventDate
select dinner;
}
public Dinner GetDinner(int id)
{
return db.Dinners.SingleOrDefault(x => x.DinnerID == id);
}
public void AddDinner(Dinner dinner)
{
db.Dinners.InsertOnSubmit(dinner);
}
public void Save()
{
db.SubmitChanges();
}
public void DeleteDinner(Dinner dinner)
{
db.Dinners.DeleteOnSubmit(dinner);
}
}
}
I have updated my database as well as LINQ data model.
return View();
You didn't pass any model to the view.
Therefore, Model is null.
This action does not send a model to the view when you make a regular GET request.
public ActionResult Index()
{
if (Request.IsAjaxRequest())
{
var dinners = _repository.FindAllDinners().Where(x => x.EventDate >= DateTime.Now).ToList();
return Json(dinners);
}
else
{
return View();
}
}
I don't know why default project does this but you can fix the NRE like this:
public ActionResult Index()
{
var dinners = _repository.FindAllDinners().Where(x => x.EventDate >= DateTime.Now).ToList();
if (Request.IsAjaxRequest())
{
return Json(dinners);
}
else
{
return View(dinners);
}
}
I am working in MVC3 Application. I am struggle to handle exceptions in my controller.
Here My Account controller is,
public ActionResult Register(NewRegister model)
{
if (ModelState.IsValid)
{
if (!IsUserLoginExist(model.Email))
{
AccountServiceHelper.CreatePerson(model);
return RedirectToAction("RegistrationConfirmation", "Account");
}
else
{
ModelState.AddModelError("","Email Address already taken.");
}
}
return View(model);
}
After I validate IsUserLoginExist I am just calling the Helper Class i.e. AccountServiceHelper for consuming a web service method like CreatePerson.
My Helper class looks like this:
public static void CreatePerson(NewRegister model)
{
try
{
try
{
var FirstName = model.FristName;
var LastName = model.LastName;
var Email = model.Email;
var Role = model.Role;
var Password = model.Password;
.....
.....
service.CreatePerson(model);
service.close();
}
catch(Exception e)
{
}
}
catch { }
}
My problem is how can I handle Exception in helper class and return to the controller.
One possibility is to handle the exception at your controller:
public static void CreatePerson(NewRegister model)
{
var FirstName = model.FristName;
var LastName = model.LastName;
var Email = model.Email;
var Role = model.Role;
var Password = model.Password;
.....
.....
service.CreatePerson(model);
service.close();
}
and then:
public ActionResult Register(NewRegister model)
{
if (ModelState.IsValid)
{
try
{
if (!IsUserLoginExist(model.Email))
{
AccountServiceHelper.CreatePerson(model);
return RedirectToAction("RegistrationConfirmation", "Account");
}
else
{
ModelState.AddModelError("", "Email Address already taken.");
}
}
catch (Exception ex)
{
ModelState.AddModelError("", ex.Message);
}
}
return View(model);
}
Like others have said, you throw it from your helper class using this method:
public static void CreatePerson(NewRegister model)
{
try
{
var FirstName = model.FristName;
var LastName = model.LastName;
var Email = model.Email;
var Role = model.Role;
var Password = model.Password;
.....
.....
service.CreatePerson(model);
service.close();
}
catch(Exception e)
{
// handle it here if you want to i.e. log
throw e; // bubble it to your controller
}
}
If an exception occurs in your helper class, and you don't specifically catch it in your helper class, it will bubble up to your controller anyway. So if you don't want to handle it in your helper class, there's no need to catch it as it will end up in your controller anyway.
throw it from your helper class
I have the following error when I click save:
the ViewData item that has the key 'SelectedCategoryId' is of type 'System.Int32' but must be of type 'IEnumerable'?
my controller:
public ActionResult IndexTwee()
{
var listCategories = new List<SelectListItem>();
listCategories.Add(new SelectListItem() {Text="foo",Value="1" });
listCategories.Add(new SelectListItem() { Text = "bar", Value = "2" });
MyViewModelTwee model = new MyViewModelTwee() { };
model.Categories = listCategories;
model.SelectedCategoryId = 2;
return View(model);
}
[HttpPost]
public ActionResult IndexTwee(MyViewModelTwee Model)
{
return View(Model);
}
my model:
public class MyViewModelTwee
{
public int SelectedCategoryId { get; set; }
public IEnumerable<SelectListItem> Categories { get; set; }
}
my view:
#model mvc3DropDown.Models.MyViewModelTwee
#using (Html.BeginForm())
{
#Html.DropDownListFor(
x => x.SelectedCategoryId,
Model.Categories
)
<button>Save</button>
}
Don't forget to rebind the list in your POST action:
[HttpPost]
public ActionResult Index(MyViewModelTwee Model)
{
var listCategories = new List<SelectListItem>();
listCategories.Add(new SelectListItem() { Text = "foo", Value = "1" });
listCategories.Add(new SelectListItem() { Text = "bar", Value = "2" });
Model.Categories = listCategories;
return View(Model);
}
Remember that only the selected value is sent when you submit the html <form>. The other values are lost so you need to refetch them from wherever you fetched them in the GET action. Of course you will externalize this code into a repository layer so that your code now looks like this:
public ActionResult IndexTwee()
{
var model = new MyViewModelTwee
{
SelectedCategoryId = 2,
Categories = _repository.GetCategories()
};
return View(model);
}
[HttpPost]
public ActionResult IndexTwee(MyViewModelTwee Model)
{
Model.Categories = _repository.GetCategories();
return View(Model);
}