问题
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})
回答1:
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...
public ActionResult CommentError(string error)
{
return View((object)error);
}
回答2:
You generally should avoid the Model
object you pass to the View()
helper being of type string
. 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 of View()
is: the View(string)
overload uses the string
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.
回答3:
As an alternative answer (just for education) you could just invoke a different overload of View()
return View("CommentError", null, error);
来源:https://stackoverflow.com/questions/4522409/why-is-my-asp-net-action-looking-for-the-wrong-view