What is the best way to transfer a JavaScript variable value from an HTML page to a Model variable within the controller?

I'm facing a challenge in my HTML page where I need to pass a variable value from the frontend to a Model class in an MVC project.

What is the most efficient way to achieve this with minimal code?

Here's what I have attempted:

Index.cshtml:

var mana = document.getElementById("ID").value;
var MyAction = '@Url.Action("MyAction", "Home")';

$.ajax({
    type: "POST",
    url: MyAction,
    data: { 'myVar': mana },
    success: function (result) {
        $('#ResultsDiv').html(result);
        @{
            var inventoryObj = Model.InventoryDataList.Where(x => x.ID == Int32.Parse(Model.grabTest)).Select(x => x.DAYOFWEEK);
            var inventoryJson = new JavaScriptSerializer().Serialize(inventoryObj);

          }

        var inventoryRefined = JSON.parse('"@inventoryJson"');
        var InventoryDataList = JSON.parse(htmlDecode(inventoryRefined));
        console.log(InventoryDataList);
    }

});

HomeController.cs:

public ActionResult MyAction(Models model, string myVar)
    {

        model.grabTest = myVar;
        //My Action Code Here
        return Json(true, JsonRequestBehavior.AllowGet);
    }

Models.cs:

public string grabTest = "";

What is the end goal here?

My LINQ query requires a parameter (ID) to filter an object list. This ID value is coming from a JS variable which necessitates using ajax.

To fulfill this requirement, I decided to use ajax to send the JS variable to an action result and store it in a public variable within Models.cs.

The concept is simple, but I'm struggling with the implementation. Any suggestions?

Answer №1

Instead of passing the value of your model as a parameter, try setting it within the MyAction method.

You can achieve this by creating a new instance of your class Models inside the code block and then assigning the value of the myVar parameter to your Models instance.

public ActionResult MyAction(string myVar)
{
   var myModel = new Models();
   myModel.testValue = myVar;
   //Add your action code here

   return Json(true, JsonRequestBehavior.AllowGet);
}

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

Creating a streamlined real-time application using the powerful combination of Django-swampdragon and AngularJS

Currently, I am using django-swampdragon along with angularjs to develop a simple Django application that displays website requests in real-time. While the Django part of the logic seems to be functioning correctly, I encounter issues when attempting to m ...

Implementing user authentication in node.js with passport

Having trouble with a basic login system using passport. I keep getting an error when logging in with the correct credentials: Error: Express 500 TypeError - Cannot read property 'passport' of undefined Oddly enough, everything works fine when ...

What kind of data type should the value property of Material UI TimePicker accept?

While reviewing the documentation, I noticed that it mentions any, but there is no clear indication of what specific data types are supported. The value sent to the onChange function appears to be an object rather than a Date object, and in the TypeScrip ...

Several socket.io sessions have been initiated

I'm fairly new to working with node.js and currently attempting to set up a server using socketio to send messages to the frontend (React). However, when running the server and multiple connections are being established, I encounter the following outp ...

Is it possible to achieve AJAX-style interaction with a stored procedure?

It seems like my approach to this problem might be totally off. I have a stored procedure that gives back a result set, which is sometimes large but usually not. This result set is then displayed in a table on the web using PHP. I am planning to add some A ...

HttpListener Invoked on Two Separate Occasions

I'm currently utilizing this code to set up an Http Server: public Server() { _httpListener = new HttpListener(); _httpListener.Prefixes.Add(Server.UriAddress); StartServer(); } public void StartServer() { ...

Unable to access property within JSON object sent via POST request

I encountered an issue TypeError: Cannot read property 'tasks' of undefined While attempting a new POST request on my API, here is the request body I am using: { "name": "example1", "description": "teaching example1", "rules" ...

What causes tests to fail with an error message SyntaxError: Unexpected token {?

Hey there! I'm encountering an issue with webpack 5 and babel while trying to run tests that were previously written. Despite following the jest documentation for configuration, I haven't been able to find a solution after exploring various forum ...

Is the provided code snippet considered a function-statement, function-expression, and function-expression-statement?

Currently, I am examining some code snippets from the EcmaScript.NET project. Specifically, I am delving into the definitions within FunctionNode.cs file. The comment above the definitions provides a detailed explanation of the three types of functions tha ...

Saving an Axios request array to a Laravel controller in Laravel using VueJs

I am working on a laravel 5.7 application that utilizes VueJS 2.0 for the front end. The issue I am facing involves two tables with a many-to-many relationship: 'commandes' and 'produits'. When trying to pass data into my 'commande ...

The issue of why padding left is not functioning correctly in Bootstrap version 5.3.1

</head> <body> <header class="bg-info "> <div class="container"> <div class="row text-white"> <div class="col-md-6 p-3 pl-6 "> ...

AngularJS allows you to dynamically disable a button based on a value in an array

I have an array containing letters from A to Z and I want to create a list of buttons using them. $scope.alphabet = "abcdefghijklmnopqrstuvwxyz".split(""); I also have another array: $scope.uniqChar = ['a', ' ...

Props does not solely rely on Vue.js for data feeding

My journey with learning vue has just started, and I recently incorporated a prop into my vue component. At first glance, the code appeared to be correct, but then something unexpected occurred. import Vue from 'vue'; import App from './A ...

The equation of jquery plus ie7 results in an undefined value

I am experiencing a strange issue in IE7 with a jQuery script. This problem seems to only occur in IE7. In summary, when I check the console window, it shows that jQuery is not defined - even though I have loaded jQuery (version 1.7.1) from my disk and can ...

Tips for avoiding the push method from replacing my items within an array?

Currently, I am diving into Typescript and VueJS, where I encountered an issue with pushing elements to my array. It seems to constantly override the 'name' property. Let me share the code snippet causing this problem: const itemsSelectedOptions ...

Unable to insert a new empty page on Xamarin

My Xamarin App is already built, but I want to incorporate a Sign Up / Login Page at the beginning. Upon opening the App, it currently opens a Sign Up Page first. I've tried adding a Blank Page with the title "Welcome to App" and a Button, but the Bu ...

What is the best way to create a fully clickable navbar item for the Bootstrap dropdown feature?

I'm struggling to make a button in a navbar fully clickable for the dropdown to open. Even when I try adding margin instead of padding, it only makes things worse. Can someone help me figure out what mistake I'm making here? Essentially, my goal ...

User authentication in MEAN Stack using passport-local and $routeProvider for routing

When it comes to logging users into my application, I am utilizing passport-local. The login process involves a function called in my AngularJS controller: $http.post('/login', $scope.user).then(function (response){ if(response.data.success) ...

Authentication not being triggered by Adal.js

I have been attempting to incorporate adal.js into my application. Here is the code I am using. Can someone please help me understand why the authentication process is not being triggered? var app = angular.module('TestWebApp', [ 'ngRout ...

Create dropdown options from JSON data

I'm attempting to populate a dropdown menu using a JSON response retrieved from an API. let dropdown = $('#LA_picker'); dropdown.empty(); dropdown.append('<option selected="true" disabled>Choose State/Province</option>& ...