开发者

ASP.NET MVC2 Creating ViewResults outside of controllers

开发者 https://www.devze.com 2023-01-04 18:02 出处:网络
Again an easy question for ASP.NET MVC 2. public ActionResult MyAction(MyModel model) { if (ModelState.IsValid)

Again an easy question for ASP.NET MVC 2.

public ActionResult MyAction(MyModel model)
    {
        if (ModelState.IsValid)
        {
           // do great stuff and redirect somewhere else

        }

        // model has errors
        return View("~/Home/Index", model);
    }

The question is that I want to return a view which is outside of the current controller. I do not want to redirect since I want to hand the model to the next view. The "View"-method does not allow to specify a controller. The above "return View.开发者_开发百科.." obviously doesn't work.

I am sure that there's a simple workaround here :)


If your view is used by more than one controller put it in the Shared views folder instead of a specific controller's view folder. Then you can simply refer to it by it's name, if different than the name of the action.


public ActionResult MyAction(MyModel model)
{
    if(ModelState.IsValid)
    {
        return RedirectAction("...");
    }
    ControllerContext.RouteData.Values["controller"] = "SomeOtherController";
    return View("Index");
}

will guide you do Index view under SomeOtherController folder.


You'll need an extension

return View("~/Path/To/View.aspx", model);
0

精彩评论

暂无评论...
验证码 换一张
取 消