【问题标题】:The model item passed into the dictionary is of type 'System.Int32', but this dictionary requires a model item of type 'IMS.Models.Dealer'传入字典的模型项的类型为“System.Int32”,但此字典需要“IMS.Models.Dealer”类型的模型项
【发布时间】:2015-09-27 17:04:54
【问题描述】:

我知道这里有很多类似的问题,但没有一个能解决我的问题。

当我访问网址时:http://localhost:42626/dealer/edit/2

发生错误:

传入字典的模型项是'System.Int32'类型, 但是这个字典需要一个“IMS.Models.Dealer”类型的模型项。

DealerController 代码:

[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);
}

我用强类型Models.Dealer 创建了View,模板是Edit

如果我定义了[HttpGet][HttpPost],为什么它不接受int并继续要求Dealer模型??

【问题讨论】:

    标签: c# asp.net-mvc controller invalidoperationexception


    【解决方案1】:

    目前如果找不到经销商 ID,您调用RedirectToAction,但忽略结果,然后尝试返回带有经销商 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);
    

    (我也可能使用异常来处理错误,而不是像这样的字符串,但那是另一回事。)

    【讨论】:

    • 就我而言,最后一行 return View(DealerId); 永远不会执行。因为如果成功则返回View(dealer),否则返回redirect to index
    • @Shaharyar:我怀疑你会发现它执行,这就是问题所在......因为你正在调用RedirectToAction,但没有返回它。请注意如何在您的 Edit(Dealer) 代码中使用 return RedirectToAction(....);,但在您的 Edit(int) 代码中您只是调用 RedirectToAction。为什么不调试它并找出答案?
    • 哎呀!我怎么能忘记这个..真的很尴尬..现在一切都很完美,谢谢:)还有一件事,你将如何通过SQL端(过程内部)的异常?
    • @Shaharyar:我会让GetDealer 方法抛出异常。仅仅因为它是从存储过程中浮现出来的,并不意味着全世界都需要看到它——将它抽象掉。
    猜你喜欢
    • 2020-09-08
    • 2013-10-18
    • 1970-01-01
    • 1970-01-01
    • 2013-10-17
    • 2014-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多