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);
}
}
Related
I am getting what appears to be an infinite loop in either LINQ or somehow JQuery. It keeps calling the Controller Method over and over.
Here's my controller method:
public ActionResult Index()
{
// TODO: decide what properties determine a need for User Action (the 'where(s)')
var viewModel = new PriorityTasksViewModel
{
BayOptions = _bayOptionRepository.GetBayOptions()
.Where(x => x.IsActive && !x.SiteVisibilityFlagsOverride).ToList()
.Select(x => new PriorityTasksBayOptionsViewModel()
{
BayGuid = x.BayGUID,
BayNumber = x.BayNumber,
PropertyId = x.PropertyId
})
.ToList(),
Properties = _propertyRepository.GetProperties()
.Where(x => !x.SiteVisibilityFlagsOverride).ToList()
.Select(x => new PriorityTasksPropertiesViewModel()
{
PropertyId = x.PropertyId,
PropertyName = x.Name
})
.ToList()
};
return View("_PriorityTasks", viewModel);
}
If I put a breakpoint in the view, I verify it's looping. What am I missing in my LINQ? I put .ToList() in there to force loading but...
View:
<h6>Properties</h6>
<table class="table">
<tr>
<th>
Name
</th>
</tr>
#foreach (var item in Model.Properties) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.PropertyName)
</td>
</tr>
}
</table>
And the JQuery at the bottom of the _Layout:(it has to show on teh menu of layout)
$(document).ready(function () {
$('#PriorityTasks').load('#Url.Action("Index", "PriorityTask")');
})
Maybe you need return a partial view instead
return PartialView("_PriorityTasks", viewModel);
I think if you want keep a layout you could use a partial view.
Controller:
public ActionResult Images(int? page)
{
int pageNumber = page ?? 1;
page = page ?? 1;
var images = db.image.AsQueryable().OrderBy(x => x.name);
var onePageOfImages = images.ToPagedList(pageNumber, pageSize);
ViewBag.onePageOfImages = onePageOfImages;
return (page == 0)
? PartialView()
: (ActionResult)PartialView("_ImageList");
}
Images.cshtml
#{
ViewBag.Title = "Image List";
}
#using PagedList;
#using PagedList.Mvc;
#Styles.Render("~/Content/PagedList.css")
<h2>Image List</h2>
#DateTime.Now.ToString()
<div id="unobtrusive">
#Html.Partial("_ImageList")
</div>
and _ImageList
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.name)
Here is my class :
public class QuestionClass
{
public static FeedbackDatabaseDataContext context = new FeedbackDatabaseDataContext();
public class Tabelfields : Question
{
//public int QuestionID { get; set; }
//public string Email { get; set; }
//public string QuestionName { get; set; }
//public string Option1 { get; set; }
//public string Option2 { get; set; }
//public string Option3 { get; set; }
//public string Option4 { get; set; }
public string SelectedOption { get; set; }
}
public static List<Question> getallQuestion(string email)
{
var list = (from q in context.Questions where q.Email==#email select q).ToList();
return list.ToList();
}
}
My view :
#model IEnumerable SQLOperation.Models.QuestionClass.Tabelfields
<p> Question</p>
#foreach (var item in Model)
{
using (Html.BeginForm("Question", "home", new {email=item.Email,item}))
{
#Html.DisplayFor(modelItem => item.QuestionName)
<br /><br />
if (item.Option1 != "")
{
#Html.RadioButtonFor(modelItem =>item.SelectedOption, item.Option1, item)
#Html.DisplayFor(modelItem => item.Option1)
<br /><br />
}
if (item.Option2 != "")
{
#Html.RadioButtonFor(modelItem => item.SelectedOption, item.Option2)
#Html.DisplayFor(modelItem => item.Option2)
<br /><br />
}
if (item.Option3 != "")
{
#Html.RadioButtonFor(modelItem =>item.SelectedOption, item.Option3)
#Html.DisplayFor(modelItem => item.Option3)
<br /><br />
}
if (item.Option4 != "")
{
#Html.RadioButtonFor(modelItem =>item.SelectedOption, item.Option4)
#Html.DisplayFor(modelItem => item.Option4)
<br /><br />
}
i = (Int16)i + 1;
if (Model.Count() == i)
{
<input name="btnsumbit" type="submit" value="Submit Feedback"
style="font-family:Segoe UI Light;font-size:medium;"/>
}
}
}
Here Is my controller
public ActionResult Question(string email)
{
return View(QuestionClass.getallQuestion(email));
}
[HttpPost, ActionName("Question")]
public void Question(string Email,List<QuestionClass.Tabelfields> q)
{
}
In class i.e. "Tabelfields" I create new property i.e. SelectedOption. I inherite the base class i.e. Question. Where Question is a table in Sql server Database.
I create strongely type view by using this
#model IEnumerable SQLOperation.Models.Question
If I change strongely type view as
#model IEnumerable SQLOperation.Models.QuestionClass.Tabelfields
I get this error
"The model item passed into the dictionary is of type 'System.Collections.Generic.List1[SQLOperation.Models.Question]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable1[SQLOperation.Models.QuestionClass+Tabelfields]'."
Why should I get this error and how can I solve this ?
Thank you,
ajay
You need to change:
#model IEnumerable SQLOperation.Models.QuestionClass.Tabelfields
to this:
#model List<SQLOperation.Models.Question>
That should fix the error.
Hope it helps.
Change your getallQuestion in model to this
public static IEnumerable<Question> getallQuestion(string email)
{
var list = (from q in context.Questions where q.Email==#email select q).ToList();
return list.AsEnumerable(); //just remove `ToList()` and place `AsEnumerable()`.
}
Try this. This should work for you.
Basically what I am trying is to create a feedback form with a question which has four answers (Radio Button) using MVC.
In View: I am able to get questions and answers in view with radiobutton to each answer.
In Controller: I am confused here.
I would like to send selected question & there answers from View to controller.
My view :
#model IEnumerable SQLOperation.Models.QuestionClass.Tabelfields
#{int i = 0;}
#foreach (var item in Model)
{
using (Html.BeginForm("Question", "home", new {email=item.Email}))
{
#Html.DisplayFor(modelItem => item.QuestionName,item)
<br /><br />
if (item.Option1 != "")
{
#Html.RadioButtonFor(modelItem =>item.SelectedOption, item.Option1, item)
#Html.DisplayFor(modelItem => item.Option1)
<br /><br />
}
if (item.Option2 != "")
{
#Html.RadioButtonFor(modelItem => item.SelectedOption, item.Option2)
#Html.DisplayFor(modelItem => item.Option2)
<br /><br />
}
if (item.Option3 != "")
{
#Html.RadioButtonFor(modelItem =>item.SelectedOption, item.Option3)
#Html.DisplayFor(modelItem => item.Option3)
<br /><br />
}
if (item.Option4 != "")
{
#Html.RadioButtonFor(modelItem =>item.SelectedOption, item.Option4)
#Html.DisplayFor(modelItem => item.Option4)
<br /><br />
}
i = (Int16)i + 1;
if (Model.Count() == i)
{
<input name="btnsumbit" type="submit" value="Submit Feedback"
style="font-family:Segoe UI Light;font-size:medium;"/>
}
}
}
My Controller :
[HttpGet]
public ActionResult Question(string email)
{
var tf = new QuestionClass.Tabelfields();
IList<QuestionClass.Tabelfields> viewmodel = new List<QuestionClass.Tabelfields>();
var q = QuestionClass.getallQuestion(email).ToList();
foreach (SQLOperation.Models.Question item in q)
{
QuestionClass.Tabelfields viewItem = new QuestionClass.Tabelfields();
viewItem.Email = item.Email;
viewItem.QuestionID = item.QuestionID;
viewItem.QuestionName = item.QuestionName;
viewItem.Option1 = item.Option1;
viewItem.Option2 = item.Option2;
viewItem.Option3 = item.Option3;
viewItem.Option4 = item.Option4;
viewmodel.Add(viewItem);
}
return View(viewmodel);
}
[HttpPost, ActionName("Question")]
public void Question(string Email,QuestionClass.Tabelfields tf)
{
}
My Model:
public class QuestionClass
{
public static FeedbackDatabaseDataContext context = new FeedbackDatabaseDataContext();
public class Tabelfields : Question
{
//public decimal QuestionID { get; set; }
//public string Email { get; set; }
//public string QuestionName { get; set; }
//public string Option1 { get; set; }
//public string Option2 { get; set; }
//public string Option3 { get; set; }
//public string Option4 { get; set; }
public int SelectedOption { get; set; }
}
public static List<Question> getallQuestion(string email)
{
var list = (from q in context.Questions where q.Email == #email select q);
return list.ToList();
}
}
I didn't get the question and it's selected option with appropriate Email in controller.
How can I get it in controller?
To, start with include a breakpoint in your view and check if the values are being passed or not.
Next, change your method signature from
public void Question(string Email,QuestionClass.Tabelfields tf)
to
public void Question(string email, QuestionClass.Tabelfields tf)
Also, I see you have used some strange syntax ( considering m also new to MVC ) where you could have simply used this
#Html.DisplayFor(modelItem => item.QuestionName)
instead of this
#Html.DisplayFor(modelItem => item.QuestionName,item)
and also, I have seen you profile, I know you are new to StackOverflow, so Welcome to StackOverflow ! you might want to read this & this as well. Cheers !
Update :
You are using this for displaying a radio button...
#Html.RadioButtonFor(modelItem =>item.SelectedOption, item.Option1, item)
what is item.Option1, I can see you have commented out Opion1,2,3,4. Or are you still using them ?
A very simple way of implementing this would be something like this
#Html.RadioButtonFor(modelItem =>item.SelectedOption, "Option1")
#Html.RadioButtonFor(modelItem =>item.SelectedOption, "Option2")
#Html.RadioButtonFor(modelItem =>item.SelectedOption, "Option3")
or you can also use,
#Html.RadioButtonFor(modelItem =>item.SelectedOption, item.Option1)
#Html.RadioButtonFor(modelItem =>item.SelectedOption, item.Option2)
#Html.RadioButtonFor(modelItem =>item.SelectedOption, item.Option3)
provided values exist in item.Option1/2/3/4 and are all of them are different.
FINAL EDIT: The problem was that ViewBag.PropName == Model.PropName;
FIX: ViewBag.PropName ===> ViewBag.PropName2
This is my first time posting; I'm new and think I messed up the layout... so sorry!
I encountered some issues with client-side validation for hidden dropdownlistfor's.
I am working with ASP.NET MVC3 and have a lot of hidden ddl on this page.
The validation however, doesn't work for some ddl's.
Has anyone ever had a problem with this before?
These are 2 properties; 1 working, 1 failing
//VALIDATION FAILS
[Required]
[Range(0, 4)]
public int TiresBack { get; set; }
//VALIDATION WORKS
[Required]
[Range(0, 4)]
public int TechnicalState { get; set; }
This is a piece the razor:
<tr>//THIS DOESN'T WORK
<td style="width: 38%;">
#txtFor("tiresBack")
</td>
//This is JQuery Star-Rating.
<td align="center" id="starsTiresBack">
</td>
<td>
#Html.DropDownListFor(model => model.TiresBack, ViewBag.TiresBack as IEnumerable<SelectListItem>, new { style = "display:none;" })
<input class="blueButton" type="button" id="btnBrandRearTires" value="#txtFor("brandTiresBack")" />
<span>#Html.ValidationMessageFor(model => model.TiresBack)</span> <span>#Html.ValidationMessageFor(model => model.BrandRearTires)</span>
</td>
</tr>
//THIS WORKS
<tr>
<td style="width: 38%;">
#txtFor("technicalState")
</td>
<td id="starsTechnicalState" align="center">
</td>
<td>
#Html.DropDownListFor(model => model.TechnicalState, ViewBag.TechState as IEnumerable<SelectListItem>, new { style = "display:none;" })
<input class="blueButton" type="button" id="btnTechnicalStateDescription" value="#txtFor("technicalStateDescriptionButton")" style="display:none;"/>
<span>#Html.ValidationMessageFor(model => model.TechnicalState)</span> <span>#Html.ValidationMessageFor(model => model.TechnicalStateDescription)</span>
</td>
</tr>
EDIT1: Initialised in the controller using this method:
public static List<SelectListItem> CreateDefaultStateList(int? selected = -1)
{
List<SelectListItem> sl = new List<SelectListItem>();
for (int i = -1; i < 5; i++)
{
SelectListItem sli = new SelectListItem();
if (i == 0 || i == -1)
sli.Text = "";
else
sli.Text = i.ToString();
sli.Value = i.ToString();
if (i == selected)
sli.Selected = true;
sl.Add(sli);
}
return sl;
}
EDIT2: The create controller. defaultstatelist is what got returned from the method posted above.
List<SelectListItem> defaultStateList = CreateDefaultStateList();
[Authorize]
public ActionResult Create()
{
FillViewBag();
ViewBag.PropX = defaultStateList;
ViewBag.TiresFront = defaultStateList;
ViewBag.TechState = defaultStateList;
ViewBag.PropY= defaultStateList;
ViewBag.PropZ= defaultStateList;
ViewBag.PropA= defaultStateList;
ViewBag.PropB= defaultStateList;
ViewBag.PropC= defaultStateList;
ViewBag.PropD= defaultStateList;
return View();
}
Typing this I notice the the default value in the method. That could be it...
==> Tried it, wasn't it. Updated code to '-1' as default value now.
The problem was that ViewBag.PropName == Model.PropName;
FIX: Rename ViewBag.PropName to something else like ViewBag.PropName2.
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();
}
}