mmutilva
mmutilva

Reputation: 18994

Optionally open a new window in controller Action

In a ASP.Net MVC 2 application I want to do the following: in the action that handles a form post I want to:

That can be done easily setting the target="_blank" attribute in the form element and adding the following jQuery script:

$(function () {
    $("form").submit(function () {
        window.location = "...";
    });
});

The View returned by the action handler will be rendered in the new window where the form is posted to.

But, let's make it a little trickier:

E.g.: Imagine that the service layer generates a pdfDocument to show to the user if everything is ok, and that pdf must be shown in a new window.

[HttpPost]
public ActionResult SomeAction(FormCollection form)
{
    var serviceMethodParams = ... // convertion from the form data somehow

    MemoryStream pdfDocument = null;

    if (!serviceLayer.DoSomething(serviceMethodParams, out pdfDocument))
    {
        // Something went wrong, do not redirect, do not open new window
        // Return the same view where error should be displayed
        return View(...);
    }

    // The service method run ok, this must be shown in a new window and the origal window must be redirected somewhere else
    return File(pdfDocument.ToArray(), "application/pdf");
}

Note that the original solution work fine when the service returns true, but if the service returns false the view showing the errors is shown in a new window and the original window is redirected somewhere else.

Upvotes: 0

Views: 2487

Answers (1)

Tejs
Tejs

Reputation: 41246

In this situation, the better option would be to simply return a URL specific to that document for the user to point to, and your ajax call, when successful, takes the URL returned from your action method, and then opens a new window itself pointing to that URL. On error, you can display errors or some such - basically, that data is folded in a Json return value.

Outside of an ajax call, the most acceptable pattern to me is to have the view re render, then attach some startup javascript to open the new window pointing to that specific URL.

Upvotes: 1

Related Questions