简体   繁体   中英

How to return ActionResult with specific View (not the controller name)

I have a method SendMail in the MVC Controller.This method calls other method ValidateLogin. This is the signature of the Validate Login:

private ActionResult ValidateLogin(Models.ResetPassword model)

When I call the ValidateLogin from SendMail, this exception appears because the controller try to search a view SendMail, but I want to load the ResetPassword View:

Global Error - The view 'SendMail' or its master was not found or no view engine supports the searched locations. The following locations were searched: ...

This is the code of the SendMail:

public ActionResult SendMail(string login)
{
        return ValidateLogin(login);
}

How Can I override the View on the return statement?

Thanks in advance

private ActionResult SendMail(string login)
{
            return View("~/Views/SpecificView.cshtml")
}

You can directly point towards specifc view by pointing to their location explicitly ..

The View method has a overload which get a string to a viewName . Sometimes you want to pass a string as a model and asp.net framework confuses it trying to find a view with the value string . Try something like this:

public ActionResult SendMail(string login)
{
   this.Model = login; // set the model
   return View("ValidateLogin"); // reponse the ValidateLogin view
}

finally, this was the solution

return View("ResetPassword", new ResetPassword
            {
                fields= fields
            });

您可以按这样的名称返回视图

return View("viewnamehere");

If SendMail was a POST, you should use the POST-REDIRECT-GET pattern

    public ActionResult SendMail(string login)
    {
        ...        
        return RedirectToAction("ResetPassword", login);
    }

    public ActionResult ResetPassword(string login)
    {
        ...
        return View("ResetPassword", login);
    }

This will protect you from a double-post in IE

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM