为什么我的ASP.NET Action会查找错误的View?

时间:2010-12-23 20:56:21

标签: c# asp.net-mvc asp.net-mvc-2

我有一个简单的动作:

    public ActionResult CommentError(string error)
    {
        return View(error);
    }

我有一个名为CommentError.ascx的简单局部视图:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<String>" %>

<%: Model %>

当我通过转到myurl.com/find/Comments/CommentError浏览直观视图时,视图显示正常......没有错误。

但是,当我转到myurl.com/find/Comments/CommentError?error=SomeErrorString时,它不会将查询字符串绑定到string error,而是查找名为SomeErrorString.ascx的视图。

为什么会这样?

编辑
注意,我确实有一个自定义的global.asax,正如我正在使用的路径所示(/ find / Comments / CommentError ::: / find / {controler} / {动作})

3 个答案:

答案 0 :(得分:6)

如上所述,MVC正在寻找与string参数相同的视图。为避免这种情况,您需要将其强制转换为对象...

public ActionResult CommentError(string error)
{
    return View((object)error);
}

答案 1 :(得分:4)

您通常应该避免传递给Model帮助器的View()对象属于string类型。这是导致错误的原因。

MVC正在寻找名为的View 字符串参数。因为这是View()的最佳匹配重载:View(string)重载使用string参数作为要加载的视图的名称。

您应该将模型数据(字符串)封装在自定义类型中,或者通过ViewData集合传递该信息。

答案 2 :(得分:0)

作为替代答案(仅用于教育),您可以调用View()

的不同重载
return View("CommentError", null, error);