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

Is ES5 essentially the same as ES6 in terms of my lambda search?

After doing a search on an array using ES6, I am having trouble figuring out how to rewrite the code in ES5 due to restrictions with Cordova not allowing me to use lambda functions... $scope.Contact.title = $scope.doctitles[$scope.doctitles.findIndex(fu ...

Updating the KML data on Google Maps V3 for a fresh look

I recently updated a map from V2 to V3 and I am working on incorporating code to automatically refresh the KML data every 30 seconds. The goal is to update the map with the latest data and display a countdown until the next refresh. Here is an example of ...

JWPlayer encounters an issue: "undefined" function is not defined

Can anyone lend a hand with this issue I'm facing? I'm attempting to upload a video using jwplayer but encountering errors. Here is the snippet of code I'm utilizing: <script type="text/javascript"> jwplayer("leg ...

I am attempting to link my Firebase real-time database with Cloud Firestore, but I am encountering import errors in the process

I am currently working on enhancing the online functionality of my chat app by implementing a presence system using Firebase Realtime Database. Here is the code snippet that I have created for this purpose: db refers to Firestore and dbt refers to the Rea ...

Sequencing the loading of resources in AngularJS one after the other by utilizing promises

While working in a service, my goal is to load a resource using $http, store it in a variable, load a child resource and store that as well. I understand the concept of promises for this task, but I am struggling with how to properly implement it in my cod ...

Strip the specified span class from the content within $(this).html()

My search function returns search results in spans. When a span is clicked, a new span with a select input and hidden input is added to another div, allowing all selected features to be posted as an array. I have a question: The $(this).html() now include ...

incapable of utilizing the $q library and promises

I am trying to make use of the variable StatusASof within the inserthtml function in the following manner. App.controller("SS_Ctrl", function ($scope, $http, $location, $window, $sce, $q) { var ShiftDetails = []; function acquireMAStatusASof(Id) { ...

Utilize jQuery to perform polling on a web service

I am looking to periodically check a webservice for new messages every hour using jQuery. The ajax call I have in mind looks like this: function checkForMessages(rowid) { $.ajax({ type: "POST", url: "MyPage.aspx/CheckForMessages", contentType: ...

Tips for effectively managing errors in Next.js getStaticProps

Currently, I am immersed in the development of my inaugural Next.JS application (Next and Strapi). All functionalities are operational, but I am interested in discovering the optimal approach to integrate error handling within getStaticProps. I have exper ...

Having trouble interacting with Xpath elements using Selenium and Java?

I have been attempting to access a search bar and submit the query without a SEARCH BUTTON. While I was able to enter the search query using javascriptexecutor, I encountered difficulty when trying to perform an Enter button action as there was no actual E ...

Issues with audio and video playback intermittently occurring on Sencha Touch 2

As a beginner with Sencha Touch 2, I am currently working on uploading images onto an iPad using Xcode. My app has audio playing on the home screen, and I want the video to start playing and the audio to stop when a specific tab is selected. However, the ...

Count the results when the textbox is changed

I have implemented a feature on my photo website where as a user types in the search box, instead of displaying suggestions, I want to show a count of results to indicate that there are photos matching their query. To achieve this, I plan to use an ' ...

The error message "TypeError ".deploy" is not a function in your Hardhat environment."

Currently, I'm in the process of developing a page for minting NFTs called astro-mint. To move forward, I need to deploy my contract using hardhat. However, when I execute this command npx hardhat run scripts/deploy.js --network dexitTestnet An erro ...

Adding Elements in Real-Time to a jQuery Mobile ListView

I'm looking to inject dynamically fetched data, formatted in JSON, into my listview. I'm struggling with how to make it work. The mobile site is fetching the object in this structure: [ {"id":1, "start":"2011-10-29T13:15:00.000+10:00", "end ...

Obtain POST information through AJAX and jQuery

post.js $.post( "/scripts/update.php", {id: testId, age: testAge}, function(data) { $(".testDiv").html(data.testId); $(".testDiv2").html(data.testAge); } ); update.php $userId = $_POST["id"]; $userAge = $_POST["age]; // contact database ...

Implementing a secure route in React that asynchronously checks user authentication status

Currently, I have a React app utilizing Auth from the aws-amplify package (version 5.3.8) and react-router-dom (version 5.3.0). Although there is a version specifically for React available, it necessitates using at least version 5.0.0 of react-scripts, whe ...

Managing browser navigation within a web application

I am currently developing a web-based application for internal use in the company I work for. The application is quite intricate, featuring numerous forms that will enable users to both view and input data, which will then be stored in a database upon savi ...

Javascript callback function

Greetings everyone! I've developed a simple nodesjs server using express. The server includes a login page where users enter their credentials to be checked against an Sqlite3 DB. My concern lies in the fact that the callback function only executes on ...

Vuelidate allows for validation to occur upon clicking a button, rather than waiting for the field

As I navigate my way through learning vuelidate, everything seems to be going smoothly, except for one thing. I can't figure out how to trigger validation only when the "Submit" button is clicked. Currently, the fields turn red as soon as I start typi ...

No pathways can be established within Core UI Angular

I've been attempting to use the router link attribute to redirect to a new page, but instead of landing on the expected page, I keep getting redirected to the dashboard. Below is an overview of how my project's structure looks: [![enter image de ...