How to Specify ContentType for a New Window in JavaScript after Submitting MVC Form

When a link is clicked, I want to open a new window with content determined by a post to my MVC controller. Here's how I currently approach it:

jQuery.ajax({
        type: "POST",
        url: '/controller/mycontroller',
        data: { mydata: data },
        error: function (xhr, status, error) {
        },
        success: function (response) {
            win_detail = window.open('', 'name');
            win_detail.document.write(response);
        }
    });

My controller is handling the HTML content and Response.ContentType and storing them in the ViewBag. In mycontroller.cshtml file, I have this structure:

@{
Response.ContentType = ViewBag.ContentType;
}

<head></head>
<body>
@ViewBag.MyHtml
</body>

The ContentType is not being set properly with this method. Any suggestions on how to achieve this? I'm open to changing my current structure for a solution.

Answer №1

If no other factors are at play, my recommendation would be to utilize a GET request and simply open the window with the provided URL.

win_details = window.open('/controller/action?mydata=' + data, 'name');

Depending on the nature of your data, you might need to serialize it differently.

var formData = $('form').serialize();
win_details = window.open( '/controller/action?' + formData, 'name');

Answer №2

Consider setting the ContentType in the controller before returning to the view, rather than passing it through ViewBag.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How do you add dynamic content to modals in AngularJS and Angular Strap based on the button that was clicked?

Is there a way to make the buttons in the AngularJS + AngularStrap modal more dynamic? Currently, they display static content, but I would like them to show the content of the first column (first name) of the exact row where the button was clicked. What is ...

A warning has been issued: CommonsChunkPlugin will now only accept one argument

I am currently working on building my Angular application using webpack. To help me with this process, I found a useful link here. In order to configure webpack, I created a webpack.config.js file at the package.json level and added the line "bundle": "web ...

What is a way to utilize Javascript in order to copy a JSON object by referencing a specific key within the object?

If you had the following JSON object example given, how could you utilize Javascript to replicate each object based on the value indicated in the "Count" key? Example Input: [ { "name":"David", "Count":2 }, { "name":"John", "Count":3 }, ] Desired Out ...

Tips for optimizing the use of JS promises?

I'm encountering issues with implementing promises in JavaScript. There are 3 asynchronous functions that rely on each other: The functions are named func1, func2, and func3 respectively. func1 produces a single result that func2 requires. func2 a ...

How can the edit feature be implemented in AngularJS?

I am struggling with implementing an edit field in AngularJS. Can someone please help me with this? Here is the code for my CRUD operations: var app = angular.module('myApp', []) app.controller('myCtrl', ['$scope', functio ...

Sending search queries from a frontend built with React.js to a backend in Express.js: What is the best approach?

I have been attempting to develop a basic search bar using react.js that will communicate with my express.js backend in order to retrieve the accurate data from the database and display it on the front-end. However, I am struggling to grasp how to transmit ...

Opening a Bootstrap Modal in React without relying on npm react-bootstrap

I've been trying to create a Modal in React.js using Bootstrap5, but I'm unable to use npm react-bootstrap for various reasons. I attempted an approach where I utilized state to set Modal classes with a button, which worked well with my NavBar, b ...

Guide to creating a ReactJS higher-order component using modern ES6 syntax

I´m attempting to create a ReactJS higher-order component using ES6 syntax. This is what I have so far: export const withContext = Component => class AppContextComponent extends React.Component { render() { return ( ...

The audio.play() HTML element fails to function in Chrome, preventing the audio from playing

I'm experiencing an issue with playing audio in Chrome when the audio.src is not called before the play call, but Firefox seems to handle it fine. Does anyone have any suggestions? You can check out the fiddle link below - http://jsfiddle.net/vn215r2 ...

What is the general consensus on combining SWR with Redux - is it considered a best practice?

I am currently incorporating both SWR and Redux into my code. Here is how I'm using them together: const vehiclesStates = useSelector(({ vehiclesStates: state }) => state); // REDUX const response = useFetch("/vehicles/states") // SWR con ...

What is the best method to center a div on the screen?

Is there a way to have a div open in the center of the screen? ...

What is the proper way to correctly invoke NuxtServerInit?

Code snippet from the VUEX repository: export const state = () => ({ z: 'sdfjkhskldjfhjskjdhfksjdhf', }); export const mutations = { init_data_for_firmenistorie2 (state, uploadDbFirmenistorieData){ state.z = uploadDbFirmenistorieD ...

How can you retrieve the original file name and line number in exceptions that are generated in Angular controllers?

When an error occurs in my Angular controller, a stack trace is generated that typically looks like the following: TypeError: undefined is not a function at new <anonymous> (…/dist/script.js:854:5) at invoke (…/dist/base-script.js:13441: ...

Loop within a promise results in undefined

Within my application, there is a function that returns a promise. Inside this function, I wait for an image in the DOM to become available and then extract that element to generate base64 data from it. getCodesOfOneMerchant(merchantDataEntry: MerchantData ...

Populating a form within an Angular.js application using PhantomJS

Looking to test an AngularJS application using PhantomJS? The first step is to fill in the login form with the username field, assuming there are no other fields involved. Typically, in a real browser, this field is managed by Angular (with the ng-model ...

Switching form field types with jquery

Hello there! I am currently attempting to use jQuery to change the type of <input> from submit to image so that an image is displayed instead of a button during the AJAX request. Here's what I have tried: $(document).ajaxStart(function() { ...

"Implementing a click event handler on a button within an iframe

On my website, I have embedded an iframe containing external content. Within the code of this iframe is a button identified by the id "XYZ." I want to create an onclick function for this button. Here's what I've attempted: $( "#XYZ" ).click(fun ...

Converting JSON data from ASP.NET MVC to a Canvas.js chart

Despite my efforts to find a solution by looking through similar posts, I am unable to resolve the issue. Within my asp.net MVC controller, I have a method called public object OfferChart() List<Det> obj = new List<Det>(); foreach ...

Input automatically establishes default values

Something strange is happening with my HTML form. When I view it on a browser, default values are appearing in the text and password inputs that I did not set. The text input shows "creator" and the password input shows "*****". This only occurs when I set ...

Encountering an "Unexpected token '{'" error while attempting to import chart.js is likely due to the import call expecting only one argument

I'm currently working on a node.js app that utilizes chart.js for visualizations. However, I'm running into errors when trying to import and use Chart. To serve chart.js to the client, I used npm to install it and then added the following code: ...