A guide on including a node as a parameter, alongside other data types, in a function using ajax within Umbraco

When attempting to pass a node and two strings as parameters to a JsonResult in Umbraco, I encountered an issue where the node variable had no value when debugging the method. Below is the JavaScript code:

function newsSub() {
    if(validateForm('newsSubscriptionForm') == true)
    {
        var name = document.forms["newsSubForm"]["name"].value;
        var email = document.forms["newsSubForm"]["email"].value;
        var node = '@SiteNode';
        $.ajax({
            type: 'POST',
            url: '/Umbraco/Surface/AjaxSurface/Newsletter',
            data: {"name":name, "email":email, "node":node},
            dataType: 'json',
            cache:false,
            success:function(data){
                var success = data.Success;
                var test = data.test;
                if(success == true){
                    document.getElementById("sendTrue").style.display='inline';
                }
                else{
                    document.getElementById("sendFalse").style.display='inline';
                }
            })
            document.getElementById("newsSubscriptionForm").style.display='none';
        }
    };

Here is the corresponding C# code:

public JsonResult Newsletter(String name, String email, Node node)
{
    INode iNode = node;

    if (ModelState.IsValid)
    {
        NewsSubscriptiontFormModel model = new NewsSubscriptiontFormModel();
        model.Email = email;
        model.Name = name;

        Dictionary<String, String> userData = new Dictionary<String, String>();

        foreach (var prop in typeof(NewsSubscriptiontFormModel).GetProperties())
        {
            if (prop.GetValue(model, null) != null)
            {
                userData.Add(prop.Name, (prop.GetValue(model, null) ?? "").ToString());
            }
        }

        if (Mailing.GenerateAndSendMail(userData, iNode))
        {
            return Json(new { Success = true });
        }
    }
    return Json(new { Success = false });
}

There seems to be a need to convert whatever needs to be typed after the 'data:' in the JavaScript code. How can this be achieved?

Answer №1

It is not possible to directly send the node id in this way. My recommendation would be to only send the node id and then locate the node in your C# code.

To find the id in your JavaScript:

var nodeId = @CurrentPage.Id;
...
data: {"name":name, "email":email, "nodeId":nodeId},

In your C# code:

public JsonResult Newsletter(String name, String email, int nodeId)
    {
        var node = new Node(nodeId);
....

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

Are there alternative methods, aside from using a computed property, that can be utilized to store a Vue route parameter in a way where

In my Vue component, I am working on passing a route parameter through XHR requests and potentially using it in other areas as well. Initially, I considered storing it as a data attribute but realized that it could be modified by someone. Then it occurred ...

How can I properly implement a Closure or IIFE to manage an onclick event in ReactJS?

I'm encountering an issue while attempting to utilize the this object in an event handler. An undefined error related to the this object keeps popping up. My development stack includes ReactJS and Redux as well. class Chat extends Component { c ...

Want to learn about Google Apps Script Web App? Join us to dive into AJAX, leverage

I'm attempting to follow the steps outlined in "Example 3: Web Response" on "this SparkFun tutorial" After implementing the code on script.google.com, I encountered an issue where I couldn't see the pin readings. Can someone provide assistance w ...

Utilizing BehaviourSubject for cross-component communication in Angular

My table is populated with data from a nodeJS API connected to methods inside my service. I attempted using a Behavior Subject in my service, initialized as undefined due to the backend data retrieval: Service: import { Injectable } from "@angular/core" ...

Error: The JS Exception has not been handled, as it is stating that 'undefined' is not an object when evaluating 'global.performance.now' in react-native-tvOS

I am currently working on a React-Native-tvOs app and despite following all the instructions from the react-native-tvOs GitHub page, I keep encountering an error when running the default template app. Even after running the script provided on the GitHub re ...

Cease hover effect animation

Whenever I hover over the main span, the animation works perfectly. However, once I move the cursor away from it, the animation continues to run. How can I make it stop, and why does it persist? $('#menu span:first').hover(function (){ functi ...

What is the best way to map elements when passing props as well?

In my code, I am using multiple text fields and I want to simplify the process by mapping them instead of duplicating the code. The challenge I'm facing is that these textfields also require elements from the constructor props. import React, { Compon ...

Issue with Angular 6 subscribe event not being caught by subject?

A new element was crafted to house a loader: @Component({ selector: 'app-loader', templateUrl: './loader.component.html', styleUrls: ['./loader.component.scss'], providers: [LoaderService] }) export class LoaderCompon ...

The implementation of useState is not functioning properly when used within a parent useState function

I am currently working with a Ticket child class where I set the total amount after changing the number of tickets. The issue I am encountering is that the setNumber function doesn't seem to work properly unless the setTotal function is commented out. ...

Leveraging AJAX with React Router

Currently tackling a project utilizing React Router, encountering some challenges with data flow. Each page triggers an AJAX call to fetch data for the component. These calls have been placed within componentDidMount: // The following code is in ES6 comp ...

Generating a JSON file by combining data from two separate lists in order to render a visually appealing stacked bar chart

Combining two lists to create a JSON for generating a stacked bar chart using JavaScript list1 = ['2019-03-05', '2019-02-20', '2019-02-20', '2019-02-19', '2019-02-18', '2019-02-16', '2019-02 ...

The JQUERY Uncaught Error: Syntax error message popped up when trying to access an unrecognized expression on the javascript: void(0)

I've encountered an issue after upgrading to jQuery 3.4.1 while using bootstrap 3. The console keeps showing this error: Uncaught Error: Syntax error, unrecognized expression: # Here is the section of code causing the error: <div class="btn-grou ...

Can the tab button be used to move to the next field?

Is it possible to navigate to the next field by pressing the tab button? If so, how can we achieve this? Currently, I am utilizing Bootstrap classes col-md-6. Thank you! <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4. ...

Transferring data between different elements in a React application

I am currently learning React and facing some challenges in terms of passing data between components. Even after reviewing various tutorials and blogs, I am still struggling to make things work. Within my project, I have two child components named Body-c ...

Modifying the calendar from a 7-day week to a 5-day week

I am currently in the process of developing a 7-day calendar (Sunday to Saturday) which is functioning well. However, I am interested in adding an option to switch it to a 5-day calendar (Monday to Friday). I was wondering if there is a way to modify the e ...

Angularjs drop-down menu changes images with animation

<body ng-controller="myCtrl"> <input type="checkbox" ng-model="loaded"/> <select ng-model="list"> <option ng-repeat="option in data.availableOptions" value="{{option.name}}">{{option.id}}</option> </select> {{list}} &l ...

Initiating a single AJAX call, yet processing multiple requests on the server side

Currently, I am facing an issue with sending ajax HTML DELETE requests from my website to a RESTful Web Service (Asp.NET MVC 4 Web-Api ApiController). The goal is to delete selected data from an HTML table by using jQuery to get the selected row. Upon cli ...

Flashing bug in the outFunction of jquery hover()

My friends and I are working on a website for a class project, but we're running into a strange issue with the outFunction part of our hover function. Whenever the mouse hovers over an element, a grey square fades in using .fadeIn(), but then immediat ...

What causes directive templates to be fetched from the server at times (resulting in a 304 response), while other times they are retrieved from the browser cache without

I've noticed that when I reload the page, Angular directive templates load in two different ways. The first way is when the browser sends a request to the server and receives a 304 response - everything works fine. However, the second way is puzzlin ...

The dictionary's get method is failing to properly retrieve the requested data

My goal is to send a value from a textbox to the server, search for this value in a dictionary, and display the result in a div. For instance, if my dictionary is d = {'a': "1", 'b': "2", 'c': "3"}, and I enter "a" in the text ...