Why is my ASP.NET Action looking for the wrong View?

为君一笑 提交于 2019-12-13 01:38:03

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!