I know there are a lot of similar questions here, but none of them could solve my problem.
When I access the URL: http://localhost:42626/dealer/edit/2
Error occurs:
The model item passed into the dictionary is of type 'System.Int32', but this dictionary requires a model item of type 'IMS.Models.Dealer'.
DealerController Code:
[HttpGet]
public ActionResult Edit(int DealerId = 0)
{
//get from database
Models.Dealer dealer = new Models.Dealer();
string Error;
if(dealer.GetDealer(DealerId, out Error))
return View(dealer);
else
{
RedirectToAction("Index");
}
return View(DealerId);
}
[HttpPost]
public ActionResult Edit(Models.Dealer dealer)
{
//if All validations are true
if (ModelState.IsValid)
{
string Error;
//save to database
if(dealer.Save(out Error))
return RedirectToAction("Index");
else
{
TempData["EditMessage"] = "An error occured. Could not update Dealer. Details: " + Error;
return Edit(dealer.Id);
}
}
return Edit(dealer.Id);
}
I've created View
with strongly typed Models.Dealer
and template is Edit
.
If I have defined [HttpGet]
and [HttpPost]
, why is it not accepting int
and keep asking for Dealer
model??
Currently if the dealer ID can't be found, you're calling RedirectToAction
, but ignoring the result and then trying to return your view with the dealer ID. I suspect you want:
[HttpGet]
public ActionResult Edit(int dealerId = 0)
{
//get from database
Models.Dealer dealer = new Models.Dealer();
string error;
if (dealer.GetDealer(dealerId, out error))
{
return View(dealer);
}
else
{
return RedirectToAction("Index");
}
}
I've updated the variable names to be more idiomatic, btw. It feels odd that a dealer itself has GetDealer
, mind you - I'd expect some kind of DealerService
to be provided to your controller via dependency injection, so you'd then have:
Dealer dealer = dealerService.GetDealer(dealerId);
(I'd also probably use exceptions for error handling rather than strings like this, but that's a different matter.)
See more on this question at Stackoverflow