Pass data from view to controller using ajax in ASP.NET MVC

I'm trying to figure out the best approach for a specific task. In my index method, I am either searching, filtering, or retrieving data from my database. I then send n items to the view. If there are more than n items, I need to implement paging. One option is to query the database again to retrieve the next set of n elements, or I could persist all the filtered or search results and just fetch the next n elements from that stored data. It seems that using sessions is not advisable, so instead of an IEnumerable of this class:

public class CatalogModel
{
    public string Price;
    public string deviceName;
    public string imgUrl;
} 

I have chosen to use this class:

public class CatalogView
{
    public IEnumerable<CatalogModel> Catalog;
    public IEnumerable<Device> Devices;

    public CatalogView(IEnumerable<CatalogModel> catalog = null, IEnumerable<Device> devices = null)
    {
        Catalog = catalog;
        Devices = devices;
    }
}

I want to store all my data in the field:

 public IEnumerable<Device> Devices 

and send it to the controller each time. However, I am unsure how to access it from JavaScript in order to post it back with ajax.

Is this a feasible approach, and would it be more efficient than querying the database each time?

Thank you!

Answer №1

  1. Begin by creating a controller action that accepts a CatalogView object.

  2. To create an object similar to your C# object, use the following line of code:

    var obj = @Html.Raw(Json.Encode(new CatalogView())
    
  3. Update your code as follows:

    public class CatalogView
    {
        public IEnumerable<CatalogModel> Catalog;
        public IEnumerable<Device> Devices;
    
        public CatalogView(IEnumerable<CatalogModel> catalog = null, IEnumerable<Device> devices = null)
        {
            Catalog = catalog;
            Devices = devices;
        }
    
        public CatalogView ()
        {
            Catalog = new List<CatalogModel>();
            Devices = new List<Device>();
        }
    }
    

    Make all your public fields public properties for conversion to and from JSON. 4. For the JavaScript portion, utilize the following code snippet:

    $.ajax({
        type: "post",
        url: "@Url.Action("YourActionName","ControllerName")",
        data: JSON.stringify(obj),
        contentType: "application/json",
        success: function (details) {
            //execute on success
        }
    }); 
    

Utilize http://www.json.org/js.html to convert your object to JSON format.

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

Transferring a zipped file from the backend of SailsJS to the frontend of React Redux via

My SailsJS Backend is responsible for generating a zip File when requested by my React App with Redux on the Frontend. I am utilizing Sagas for asynchronous calls and fetch to make the request. In the backend, I have attempted various methods such as: //z ...

Sending form data via Ajax for a specific field ID

When sending data to an ajax script, I usually create a form tag and assign it an id like this: <form id="myForm"> Then, in the ajax script, I include the following code: data: $('#myForm').serialize(), This sends all the form data. How ...

Reverse the animation of the storyboard when a click event occurs

In my project, I have a range control with a sequenced storyboard for its actions. I've successfully implemented the play and pause buttons to control the animation. However, I'm now working on adding a functionality to reverse the animation when ...

Tips for transferring information from a preexisting JSON document to a MongoDB database using C#:

I am seeking assistance to add data from a JSON file to MongoDB. I have attempted to use the following code, but encountered an error message: "FormatException : Cannot deserialize a 'BsonDocument' from BsonType 'Array'." :( :( Here is ...

One required positional argument is needed in `update_one()`: 'update' is missing

I've exhausted all possible options, but I can't seem to make it work. Any suggestions on how I can get this code to function properly? I attempted using ajax_data to update the values, but it was unsuccessful. The main goal of this code is to al ...

What are the appropriate situations to utilize Q.defer versus using Promise.resolve/reject?

I've been working with nodejs and I'm curious about when to use Q defer over Promise.resolve/reject? There are numerous examples of both methods, such as: // using Q defer function oneWay(myVal) { var deferred = Q.defer(); if (myVal < 0) ...

What is the process for importing an md file in a create-react-app project using JavaScript?

Attempting to execute the blog example provided on Material UI's getting started page. However, encountering an issue with the source code: Inside blog.js import post1 from './blog-post.1.md'; . . . return( <Main>{post1}<Main/> ...

What is the best way to retrieve the updated window dimensions following a rotation of an iPad screen?

I need to update the size of a specific element on a webpage based on screen rotation, especially for iPads and all other mobile devices. The new dimensions should be calculated according to the updated screen size. While attempting to implement this, I e ...

Working with node.js to set up an ordering function

I am working with node.js and express3. To use mongodb, I decided to install the mongo-lazy package. This is the simple GET router I have set up: var db = require('mongo-lazy').open({ db: 'somedb', host: '127.0.0.1' ...

Exploring the Functions of JavaScript with Google's Cloud Storage

I have been attempting to upload images into buckets on Google Cloud Storage using the JSON API and the Javascript sample provided in the documentation. Although I am able to successfully upload pictures, I am encountering an issue where it prompts me to ...

Turning $.post into $.ajax: A step-by-step guide

I need help with converting my $.post code to $.ajax. Here is the code snippet: $.post("../admin-login", { dataName:JSON.stringify({ username:uname, password:pass, }) }, function(data,status){ console.log("Data:"+data); answer = data; ...

Using AJAX to load a PHP file in CodeIgniter is a great way to

I'm a beginner in the world of web development and I need help with loading my PHP file containing HTML content to update the span element. My framework of choice is CodeIgniter. Every time I try, I encounter an error. Below is my JavaScript code: ...

Unable to display information from a repeated `textarea` in ngRepeat

Check out my code on Plunker: https://plnkr.co/edit/rBGQyOpi9lS0QtnCUq4L I'm trying to log the content of each textarea when typing, using the printStuff() function: $scope.printStuff = function(customize, item) { console.log(customize[item.inde ...

Retrieve information stored in a component's data variable

After creating a Vue repository using vue init webpack my-app My main.js file looks like this -- // The Vue build version to load with the import command // (runtime-only or standalone) has been set in webpack.base.conf with an alias. import Vue fro ...

Step-by-step guide for inputting a sophisticated formula in exceljs using JavaScript

Currently, I am working on a project that involves exporting data into multiple xlsx sheets. One of the sheets requires me to add a formula in cells that meet certain conditions before adding data from the first sheet. Here is an example: Ref !== null ? wo ...

Troubleshooting issues with hint functionality and fullscreen mode in CodeMirror within a jQuery layout

I have integrated the codeMirror library into the UI Layout Plug-in on my website. Challenges: When using CodeMirror within the layout, the Full Screen Editing feature does not work as intended. Press F-11 to zoom in and Esc to exit full screen mode. I ...

Transform your traditional sidebar into a sleek icon sidebar with Semantic UI

I am working on customizing the semantic-ui sidebar. My goal is to have it minimize to a labeled icon when the toggle button is clicked. However, I am having trouble with the animation and getting the content to be pulled when I minimize it to the labeled ...

Encountering an issue when deploying a project using node, webpack, express, and mysql to Heroku. The error message states: "Uncaught ReferenceError: regeneratorRuntime is not

I've been going around in circles ever since I started this project, and now the code is all over the place. This is my first time working on a node project without using a framework, and I'm starting to regret not choosing PHP. Anyway, here&apos ...

Trigger notifications exclusively for specific hyperlink texts that are selected

I'm facing an issue where I need to notify the user when a specific link text for a hyperlink is clicked. The code provided here showcases the problem I am currently encountering. At the moment, the alert triggers whenever any link text is clicked, ra ...

Combine NPM dependencies into a single JavaScript file

Attempting to integrate Swig, a template language, into Parse Cloud Code with Express can be quite challenging. Parse Cloud Code is a Node/Express host that has restrictions on using NPM, which can be frustrating. However, there may still be a way to load ...