Ayyash
Ayyash

Reputation: 4409

RewritePath instead of return view in MVC

Is there a way to rewrite the path displaying a different view instead of RedirectToAction or Redirect? I don't want the url to change, but notice the regular RewritePath cannot be "returned", so the action actually keeps going after it!

public ActionResult Register(){
    if (somehting){
        HttpContext.RewritePath(url);
        // I want it to stop here, somehow, but it keeps going and expects a return statement
    }
    return View();
}

Update: I just noticed when I use the one circulating in stackoverflow (with ProcessRequest) if I run F5 it works, but when I access directly it gives me the "'HttpContext.SetSessionStateBehavior' can only be invoked before 'HttpApplication.AcquireRequestState' event is raised." which means im missing something in IIS setup, what is it? :s

[Update] To be clear on this, I need to rewrite a "url" not an action or view name, it must be a url, like good old RewritePath(url)

Upvotes: 1

Views: 3052

Answers (4)

Ayyash
Ayyash

Reputation: 4409

This is what I finally did, inspired by Stephen's answer to create a method that handles the returned views:

First the global method (here its named Timeout in Home controller) under HomeController.cs:

public ActionResult TimeOut(){
    return View("TimeOut"); // the string is essential
}

else where:

if (soemthing){
    return new HomeController().TimeOut(); }

any objections? wrong doings?

Upvotes: 1

steve v
steve v

Reputation: 3540

In addition to Cyril's answer, you could directly call another Controller method and return the result of that method. Let's say you have a method as follows that returns what you want to return.

    public ActionResult SpecialRegistration()
    {
       //TODO:  implement logic that does stuff
       return View();  // Shows the View named SpecialRegistration
    }

Now in your regular Register method you can just call it

    public ActionResult Register(){
        if (something){
            return SpecialRegistration();
        }
   }

Upvotes: 0

Kuqd
Kuqd

Reputation: 497

Return a different view with a different model and the url won't change.

like this let's say you have a view called Hello.cshtml.

return View('Hello',Model);

So you return a different View than the action, the url stay the same, the view change for the user.

Upvotes: 0

B. Bilgin
B. Bilgin

Reputation: 783

For only action redirect:

Use sample return RedirectToAction("Action","Controller",new {id=1});

For Url redirect:

Can use return Redirect(URL);

also expression after HttpContext.RewritePath(url); use response.end();

Upvotes: 1

Related Questions