C# 传入字典的模型项的类型为';System.Int32';,但本词典需要类型为';IMS.车型.经销商';
我知道这里有很多类似的问题,但没有一个能解决我的问题 当我访问URL时: 发生错误:C# 传入字典的模型项的类型为';System.Int32';,但本词典需要类型为';IMS.车型.经销商';,c#,asp.net-mvc,controller,invalidoperationexception,C#,Asp.net Mvc,Controller,Invalidoperationexception,我知道这里有很多类似的问题,但没有一个能解决我的问题 当我访问URL时: 发生错误: [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 V
[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);
}
传入字典的模型项的类型为“System.Int32”,
但本词典需要“IMS.Models.Dealer”类型的模型项
经销商控制器代码:
[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);
}
我已经用强类型的模型创建了视图
。经销商
和模板是编辑
如果我已经定义了
[HttpGet]
和[HttpPost]
,为什么它不接受int
并一直询问经销商
型号???当前如果找不到经销商ID,您正在调用重定向到操作
,但是忽略结果,然后尝试使用经销商ID返回您的视图。我怀疑您想要:
[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");
}
}
顺便说一句,我已经更新了变量名,使其更为惯用。经销商本身拥有GetDealer
,这让人感到奇怪,请注意-我希望通过依赖项注入向您的控制器提供某种DealerService
,这样您就可以:
Dealer dealer = dealerService.GetDealer(dealerId);
(我也可能使用异常来处理错误,而不是像这样的字符串,但那是另一回事。)在我的例子中,最后一行
返回视图(DealerId)代码>将永远不会执行。因为如果成功,它将返回查看(经销商)
,否则重定向到index
@Shaharyar:我怀疑您会发现它将执行,这就是问题所在。。。因为您正在调用重定向到操作
,但没有返回它。注意如何在编辑(经销商)
代码中使用返回重定向操作(…)代码>但在编辑(int)
代码中,您只需调用重定向到操作
。为什么不调试一下并找出答案呢!我怎么能忘记这件事。。真不好意思。。现在一切都很完美了,谢谢:)还有一件事,您将如何从SQL端(过程内部)处理异常?@Shaharyar:我将让GetDealer
方法抛出异常。仅仅因为它是从一个存储过程中出现的,并不意味着整个世界都需要看到它——把它抽象出来。