Transferring the outcome of JavaScript to a View

Hey there, I have a question as I am quite new to working with Asp.net. I have a Javascript code where I want to pass data to my Controller.

<script type="text/javascript">
        $("#SearchButton").on("click", function () {
            var $sucheMoped = [];
            $("#tab_logic tbody tr")
                .each(function () {
                    var $Item = $(this);
                    var suchfeld = $Item.find("td > input[name='Suchfeld']").val();
                    var schluessel = $Item.find("td > select[name='Suchschluessel'] > option:selected").val();
                    alert(suchfeld + "&&&" + schluessel);
                    $sucheMoped.push({
                        Suchfeld: suchfeld,
                        Suchschluesseltyp: schluessel
                    });
                });
            window.open('@Url.Action("MainView","MainView")?SuchObject='+$sucheMoped);
        })
    </script>

I am simply trying to send the "sucheMoped" from my JavaScript code to my Controller. My Controller is expecting an IEnumerable of Objects with properties Suchfeld and Suchschluesseltyp.

Does anyone have any ideas on how to approach this?

Thanks everyone.

Answer №1

To start off, the way you call the controller action needs to be adjusted. You should convert the array into a string using the JSON.stringify() method.

Here is how it should be done:

window.open('@Url.Action("MainView","MainView")?SuchObject='+JSON.stringify($sucheMoped));

Next, you will need to create a custom model binder to bind your array with the action parameter. The example below demonstrates a basic array model binder which may need to be customized further according to your requirements and error handling needs.

public class ArrayModelBinder: DefaultModelBinder
{
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var rawArray = controllerContext.HttpContext.Request.QueryString["SuchObject"];
        var array = JsonConvert.DeserializeObject<IEnumerable<MyObject>>(rawArray);

        return array;
    }
}

In this code snippet, I retrieve the query string from the URL, then use JsonConvert.Deserialize<T> method to parse and return it.

Simply adorn the parameter in your controller's action with the custom model binder like shown below:

[HttpGet]
public ActionResult Search([ModelBinder(typeof(ArrayModelBinder))]IEnumerable<MyObject> SuchObject)
{
    return View(SuchObject);
}

Edit

If you want to open a new browser window or tab, you can make use of window.open. However, to navigate to another location without opening a new tab or window, utilize the window.location property as follows:

window.location = '@Url.Action("Search", "Home")?SuchObject=' + JSON.stringify(array);

Answer №2

When utilizing the jQuery.ajax function, it becomes possible to send intricate objects through the data parameter.

$.ajax({
    url: '@Url.Action("MainView", "MainView")',
    type: 'GET',
    data: { 'SuchObject': $sucheMoped },
    success: function (htmlContent) {
        // Transfer content to a new window (adapted from http://stackoverflow.com/a/23379892/1450855)
        var w = window.open('about:blank', 'windowname');
        w.document.write(htmlContent);
        w.document.close();
    }
});

Answer №3

If you want to trigger an action method in your controller and return a JavaScriptResult type, you can utilize the jQuery library's $.getScript function.

$.getScript("HomeController", "Display")

// HomeController
private JavaScriptResult Display()
{
    string message = "alert('Hello World');";

    return new JavaScriptResult { Script = message };
}

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

Mastering the correct usage of parsing and stringifying in JSON is

When I receive data from the server, it looks like this: ['model':{"category":[{"id":1}],"food":[{"id":1}].... // lengthy json code I am wondering how to extract the category id and food id using jQuery or JavaScript. I have tried using JSON.p ...

Incorporating Select2 into Your Laravel 4 Application

I've recently incorporated select2 into my multiselect search filter, but I'm struggling to integrate it effectively. Here's the method I'm using: public function getContactByName($name) { return Contact::select(array('id&apo ...

I'm having difficulty implementing a vue-awesome icon on my project

I am attempting to utilize the standard window-close icon from vue-awesome. I have imported my vue-awesome using the following code: import 'vue-awesome/icons'; import Icon from 'vue-awesome/components/Icon.vue'; Vue.component('i ...

Passing a string array from View to Controller using Url.Action in MVC framework

I am facing an issue where I have a method that returns an array (string[]) and I am attempting to pass this array of strings into an Action. However, I am currently unable to pass my parameters as expected. Being new in MVC3, I would appreciate any insi ...

What is the process for exporting an SVG file from a web page?

<svg class="paint" version="1.1" xmlns="http://www.w3.org/2000/svg"> <rect class="svgobject" x="458" y="165.28750610351562" width="142" height="56" fill="black" stroke="black" id="154" transform="translate(0,0)"> </rect> </svg> ...

Having a minor problem in attempting to retrieve a random value

Having trouble generating a random number from a function. Can someone help explain? const MyButton = document.querySelector(".Flipper"); MyButton.addEventListener("click", recordLog); function recordLog (){ MyButton.style.backgr ...

Encountered an issue while attempting to handle the image uploaded via React using Node.js and Sharp

I have integrated a feature to allow users to upload their profile picture using the frontend, which is functioning properly. However, the backend keeps rejecting the uploaded image files, even if they are in jpeg, jpg, or png format. const storage = multe ...

What is the best way to include a &nbsp; in a map function using JavaScript?

A challenge I encountered while working in React is as follows: <Grid item> { rolePriorities.map((rp, index) => ( <Chip key={index} label={rp} color="primary" sx={{ color: "whitesmoke" }} /> ...

Achieving the resolution of a Promise amidst the failure of a separate promise

I need to handle a situation where a promise is resolved regardless of the success or failure of an ajax call. I attempted to use the following code snippet: new Promise(function(resolve, reject) { $.ajax({ url: "nonExistentURL", headers: { ...

Using Three.js to transfer one object's rotation to another object

I have been attempting to transfer one object's rotation to another with no success using the following methods: //The first method rotates much faster than the original object's rotation boxme1.rotateOnAxis(new t.Vector3(0,1,0), cube.rotation.y ...

Guidelines for displaying a single record from a JSON object in an MVC view sequentially

Recently, I've been facing a situation where I need to retrieve a list of values in JSON format from my controller and display only the first record on my form. Then, upon pressing the down arrow key, I want to display the second record and so on. I& ...

Leveraging ES6 with jQuery in Symfony 4

Currently working on a simple app using Symfony 4 and trying to add custom triggers in JavaScript. Having trouble getting my additional code to work as expected, even though it's compiled by Webpack via encore. It seems like my event is not triggering ...

Restful Spinner

app.config(function(RestangularProvider) { RestangularProvider.addRequestInterceptor(function(element) { console.log("Request initiated"); return element; }); RestangularProvider.addResponseInterceptor(function(data) { ...

Three.js tutorial: Rotating items on each axis individually

Looking to create an interactive 3D item that users can rotate with their mouse freely? I experimented with using three quaternions, one for each axis, and then multiplying them together to determine the final position of the item. // Initializing xQuat, y ...

Changing the parent scope from the child component does not automatically reflect changes in an ng-repeat

I am facing an issue with the communication between a child controller and a parent controller. I have a function that adds data to a parent array which is used in an ng-repeat directive. Although the parent array gets updated correctly and its length is ...

ASP.NET AJAX MaskedEditExtender is a powerful tool that allows developers

Hey there, I am currently using the MaskedEditExtender to format a money value input. The issue I am facing is that when the input is given, it progresses from left to right whereas I would like it to progress from right to left. Here's the code snipp ...

Restricting Meteor Publish to specific user (admin) for all collections

Is there a method to exclusively publish all meteor collections to users with the role of {role: "admin"}? The meteor autopublish package grants database access to all clients. Are there any techniques to utilize the autopublish package while implementing ...

Ways to convert a buffered document into an object

Currently, I am transferring a file to my express server and because I am utilizing a cloud service, my file is pre-processed into a buffer <buffer 2o 7x 52o...>. While I know I can convert this to text by using JSON.stringify(buffer), once it's ...

The search function in Select2 is not displaying the desired result

I'm encountering an issue with the search functionality when it uses Ajax to load data from a JSON file. For example, if I search for Yemen, the record for Yemen does not get selected or highlighted properly. Here is the complete source code - could ...

explore a nested named view using ui-router

My app has a view called mainContent. <div class = "wrapper" ui-view = "mainContent"> </div> There is only one route for this view. $stateProvider .state("home", { url: "/home", vi ...