clement
clement

Reputation: 4266

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

Upvotes: 35

Views: 115513

Answers (5)

clement
clement

Reputation: 4266

Finally, this was the solution:

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

Upvotes: 14

Kaushik Vatsa
Kaushik Vatsa

Reputation: 776

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

You can directly point toward specific view by pointing to their location explicitly.

Upvotes: 64

Spencer Sullivan
Spencer Sullivan

Reputation: 575

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

Upvotes: 5

Mairaj Ahmad
Mairaj Ahmad

Reputation: 14624

You can return view by a name like this

return View("viewnamehere");

Upvotes: 2

Felipe Oriani
Felipe Oriani

Reputation: 38638

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
}

Upvotes: 10

Related Questions