为什么我的 ASP.NET Action 寻找错误的视图?
我有一个简单的操作:
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}/{action} )
I have a simple action:
public ActionResult CommentError(string error)
{
return View(error);
}
I have a simple partial view called CommentError.ascx:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<String>" %>
<%: Model %>
When I browse to the view directy by going to myurl.com/find/Comments/CommentError
the view displays fine... no errors.
But, when I go to myurl.com/find/Comments/CommentError?error=SomeErrorString
, instead of binding the querystring to string error
, it looks for a view called SomeErrorString.ascx
.
Why is this happening?
Edit
Note, i do have a custom global.asax as indicated by the paths I'm using (/find/Comments/CommentError ::: /find/{controler}/{action})
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如前所述,MVC 正在寻找与字符串参数同名的视图。为了避免这种情况,您需要将其转换为一个对象......
As mentioned, MVC is looking for a view named the same as the string parameter. To avoid this, you need to cast it to an object...
通常,您应该避免传递给
View()
帮助器的Model
对象为string
类型。这就是你的错误的原因。MVC 正在寻找一个
View
命名您的字符串参数。因为这就是View()
的最佳匹配重载:View(string)
重载使用string
参数作为视图的名称加载。您应该将模型数据(字符串)封装在自定义类型中,或者通过
ViewData
集合传递该信息。You generally should avoid the
Model
object you pass to theView()
helper being of typestring
. This is the cause of your error.MVC is looking for a
View
named what your string parameter is. Because that's what the best matching overload ofView()
is: theView(string)
overload uses thestring
parameter as the name of the view to load.You should encapsulate your Model data (the string) in a custom type, or pass that info via the
ViewData
collection instead.作为替代答案(仅用于教育),您可以调用 View() 的不同重载
As an alternative answer (just for education) you could just invoke a different overload of View()