Using MVC to create dynamic JavaScript functions that call actions

Having trouble with dynamic JavaScript onchange event not firing in my application. Here's the code snippet from my action result:

public ActionResult About()
        {
            ViewBag.Script = "<input type='text' name='myName' onchange='nameChange(this)' /><br/>" +
                "<script type='text/javascript'>function nameChange(d){" +
                "$('[name=myEmail]').val('');" +
                "$.ajax({type: 'POST', url: '/Home/Search', data: '{name:d}', " +
                "contentType: 'application/json; charset=utf-8', dataType: 'html'," +
                "success: function(data) { $('[name=myEmail]').val(data.toString());            }        });" +
                "}</script>"
                + "<input type='text' name='myEmail' />";
            ViewBag.Message = "Your application description page.";

            return View();
        }

This is how my controller looks like:

public ContentResult Search(string name)
        {
            return Content("<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e9818c858586a98e84888085c78a8684">[email protected]</a>");
        }

However, I'm facing an issue where the action URL is not being recognized. Can someone provide assistance with this problem?

Here's a part of the cshtml file:

@if (ViewBag.Script != null)
{

    @Html.Raw(ViewBag.Script)

}

Answer №1

By specifying

contentType: 'application/json; charset=utf-8'
, you are indicating that the data you will send with your $.ajax request is in JSON format. However, the current data being sent is not in JSON format. To rectify this, you should create a JSON object by changing the data parameter of $.ajax to:

data: JSON.stringify({name:d})

Additionally, since you have specified a POST request in your $.ajax call, the Controller Action in your code should be decorated with a [HttpPost] attribute like so:-

[HttpPost]
public ContentResult Search(string name)
{
    return Content("<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="88e0ede4e4e7c8efe5e9e1e4a6ebe7e5">[email protected]</a>");
}

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

Querying a map within a Mongo function results in an empty variable when accessed outside of the function, but

Currently, I am facing an issue while trying to create an array of objects using the map function in Mongo and node/express JS. Strangely, when I utilize console.log outside the map function, the array appears empty. However, within the map function, each ...

The functions.php file is failing to execute the JavaScript files located in the js folder

I've been attempting to incorporate a JS accordion into my Wordpress blog, but I seem to be encountering issues with the accordion.js file not loading through the functions.php file. Interestingly enough, when I manually add the js code in the header ...

The AngularJs project is currently experiencing issues when trying to function as a single page web application

I'm currently working on incorporating AngularJS into an existing web project that uses jQuery. Here is a snippet of my code: <div class="medya" ng-repeat="d in data" masonry-item-dir> <a href="{{d.Url}}" class="onizleme"><img src="{ ...

Encountering an unusual hash code when implementing Google Tag Manager in a Next.js project was

I am currently using Next.js and have added Google Tag Manager through a script <script dangerouslySetInnerHTML={{ __html: `(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start': new Date().getTime(),event:'gtm.js'});var ...

How can I access the parameter value for the tooltip callback function within echarts?

I am attempting to retrieve the value for this specific Apache EChart from within the callback function of the tooltip formatter. When I manually input the value, the formatting function operates correctly: formatter: (params:any) => `$ ${Math.round(pa ...

"Struggling with setting the default checked state for single and multiple checkboxes? The ng-init method with checkboxModel.value=true seems to be ineffective – any suggestions

<input type="checkbox" ng-model="isChecked.value" ng-true-value="'yes'" ng-false-value="'no'" ng-click='handleCheckboxChange(isChecked.value, idx);' ng-init="isChecked.value=true" /> ...

Setting up additional requirements in a subfolder within play.js

Seeking assistance with an issue in play.js on Sandbox. Attempting to install a dependency but my package.json is not located in the root folder; it's stored within a folder named frontend. How can I install them when the package.json is inside that f ...

Tips for inserting a value into a specific location within an array using JavaScript

I am working with an array of objects that looks like this: const array = [ { id: 1 }, { id: 2 }, { id: 3 }, { id: 4 } ]; My task is to add a new entry to this array, but it needs to be inserted at a specific position. For instance, when adding { ...

Is there a way to determine if a browser's Storage object is localStorage or sessionStorage in order to effectively handle static and dynamic secret keys within a client?

I have developed a customizable storage service where an example is getExpirableStorage(getSecureStorage(getLocalStorage() | getSessionStorage())) in typescript/javascript. When implementing getSecureStorage, I used a static cipher key to encrypt every ke ...

Steps for designing an HTML table that expands and collapses partially

I am currently revamping an old "Top Screens" page by expanding the display from the top 30 to the top 100 in a basic html table format. However, I only want to show the top 20 on page load with an expand/collapse feature. While I have come across examples ...

Incorporate create-react-app with Express

Issue - I am encountering a problem where I do not receive any response from Postman when trying to access localhost:9000. Instead of getting the expected user JSON data back, I am seeing the following output: <body> <noscript>You need to ...

Dynamically insert letters into each row as the HTML table increases

How can I display dynamically increasing alphabets in a newly generated cell on the left side of each row, based on the option selected in a dropdown list? These alphabets will serve as bullet points or serial numbers for the text boxes in each row. View ...

Ways to retrieve only the chosen option when the dropdown menu features identical names

How can I retrieve only the selected value from the user, when there are multiple select options with the same class name due to dynamic data coming from a database? The goal is to submit the data using Ajax and have the user select one option at a time. ...

Contrasts between the storage of data in a static function versus a static object

Trying to figure out the best way to reset a react class component back to its initial state, I came across two different implementations. In my own version, I created an object with initial values and set the component's state equal to it: // My imp ...

Uploading files using Multipart/form-data in Node.js and Express.js

With the removal of express.multipart from the Express 4.x library, what approach would be most effective for managing file uploads in expressjs? ...

What is causing my component callback to not function properly?

I'm currently following a tutorial on AngularJS callbacks from . In my code at https://plnkr.co/edit/dxyI0p0pZFZdMalLfvXO?p=preview, I've attempted to showcase the issue I'm encountering. I have initialized the component in three different w ...

How is it that this JavaScript task does not trigger an error: const a = (1, 2, 3, 4);

let x = (5, 6, 7, 8); console.log(x); let y = 5, 6, 7, 8; console.log(y); In the example above, x will be assigned a value of 8, while the second line will result in an error. What is the reason behind the success of the first assignment? How does it qua ...

Flot Graphs: A unique dual-axis line chart with the ability to stack data on one axis

Is it possible to utilize the FLOT Javascript library for creating a chart with dual axis and three data sets? I am specifically looking to have one data set on the left axis and two on the right axis. Ideally, I want to stack the two datasets on the right ...

Is there a way to redirect conditionally right after returning index.html in an AngularJS single page application?

We have a website that utilizes Asp.net MVC to deliver an index.html file when accessing the root, followed by AngularJS 1.2.4 for a Single Page Application setup. I am in need of redirecting to a specific route immediately upon loading the SPA for users w ...

JavaScript client side event that references the sender object ID in an aspx file

Can someone provide assistance with an issue in the code block below? function(s, e) { form1.hfRaiseEvent.value = s.ID; } This particular function is triggered when the Client Side Click Event occurs. From my understanding, s refers to the Sender Obj ...