"An ActionResult is received as null when the model is passed as an

Has anyone encountered a situation where the model is null when passed to the controller? I inserted an alert in the ajax call to verify the value and it seemed correct, but upon debugging on the first line of the controller's ActionResult, it shows as null.

Thank you in advance

AJAX Call

function DeleteFromList(_id) {
    var _model = $('#createLPathForm').serialize();
    alert(_model);
    event.preventDefault();
    $('#createLPathForm').validate();
    if ($('#createLPathForm').validate()) {
        var request = $.ajax({
            type: "POST",
            url: "/umbraco/Surface/CreateLPath/DeleteItems",
            dataType: 'json',
            data: { 'model': _model, 'id': mId },
            success: function (data) {
                $("#lpPartial").html(data);
            },
            error: function (data) {
                //$('#failModal').removeClass("d-none").addClass("d-block");
            }
        })
    }
}

Controller

[HttpPost]
        [ActionName("DeleteItems")]
        public ActionResult DeleteItems(CreateLPathModel _model, string id)
        {
            List<ModuleItems> items = _model.SelectedModuleList;
            ModuleItems itemToDelete = new ModuleItems();
            foreach (var item in items)
            {
                if (item.ArticleGuid == id)
                {
                    itemToDelete = item;
                }
            }
            _model.SelectedModuleList.Remove(itemToDelete);
            itemToDelete.isSelected = false;
            _model.SelectModulesList.Add(itemToDelete);

            foreach (var key in ModelState.Keys.Where(m => m.StartsWith("SelectModulesList")).ToList())
                ModelState.Remove(key);

            foreach (var key in ModelState.Keys.Where(m => m.StartsWith("SelectedModuleList")).ToList())
                ModelState.Remove(key);

            return PartialView("~/Views/Partials/LearningPaths/_CreateLPath.cshtml", _model);
        }

Answer №1

If you are serializing your form and sending it as a property to your data model, one solution to your issue is to assign the data property with your _model variable and pass your mId variable as a query string:

function RemoveFromList(_id) {
var _model = $('#createLPathForm').serialize();
alert(_model);
event.preventDefault();
$('#createLPathForm').validate();
if ($('#createLPathForm').validate()) {
    var request = $.ajax({
        type: "POST",
        url: "/umbraco/Surface/CreateLPath/DeleteItems?id=" + mId,
        dataType: 'json',
        data: _model,
        success: function (data) {
            $("#lpPartial").html(data);
        },
        error: function (data) {
            //$('#failModal').removeClass("d-none").addClass("d-block");
        }
    })
  }
}

Answer №2

To achieve this, follow these steps:

Firstly, create a class structured as follows:

public class MainObject
{
   public CreateLPathModel _model {get; set;}
   public string id {get; set;}
}

Next, implement the Controller method like so:

[ActionName("DeleteItems")]
public ActionResult DeleteItems([FromBody] MainObject obj)
{
   // Access Obj._model in the method
}

Lastly, ensure data is passed correctly in the AJAX call:

data: JSON.stringify({ 'model': _model, 'id': mId });

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

Tips for maintaining authentication in a Next.js application with Firebase even when tokens expire or the page is refreshed

Struggling with firebase authentication flows while building an app using firebase and next.js. Everything was going smoothly until I encountered a bug or error. When my computer remains logged in to the app for some time and I refresh the page, it redirec ...

AngularJS: Issues with data retrieval in parallel in $http get requests within a $.each loop

Attempting to fetch data for multiple IDs is the goal: (Simplified version, aiming to clarify) Controller: var idList = [39,40,41]; $.each(idList, function(key, value){ var dataObject = { type: "test", id: value }; var getData = DataFactor ...

Converting Dynamic Objects into Class Instances

I've been grappling with this issue for the past day or so and I just can't seem to pinpoint why it's occurring. Right now, my goal is to deserialize a dynamic object into a class for usage. However, no matter what I do, I keep encountering ...

Error: The function setOpenModal is not defined

I'm currently working on creating a login modal popup that will appear when a button inside a navbar is clicked. However, I'm encountering the following error: TypeError: setOpenModal is not a function Despite going through various discussions ...

Experience a seamless transition as the background gently fades in and out alongside the captivating text carousel

I have a concept that involves three background images transitioning in and out every 5 seconds. Additionally, I am utilizing the native bootstrap carousel feature to slide text in synchronization with the changing background images. Solving the Issue ...

Tips for keeping the hover effect of a sibling element in Material-UI

Card Component import image from "../../Assets/pic.jpg"; import React, { useState } from "react"; import { makeStyles } from "@material-ui/core/styles"; import Card from "@material-ui/core/Card"; import CardActionAre ...

Tips on extracting the ID number prior to locating an element by its ID using Python Selenium

I am currently attempting to automate sending LinkedIn connection requests using Python with Selenium. However, I am facing an issue where the ember number value keeps changing every time I try to copy the id of the button. Sometimes it shows as #@id=" ...

Interact with elements using Selenium with dynamic target IDs and AJAX

Currently, I am utilizing selenium for automating various IT administrative tasks. One specific task involves swapping out external drives on a NAS system accessed through an internal webpage. The web interface of the NAS appears to utilize AJAX, which dyn ...

Why is the image popup feature not functioning properly? What could be causing the issue?

I'm experiencing issues with the functionality of my HTML file and image popup. I've attempted to troubleshoot it multiple times without success. Here is a code snippet for reference: You can view and run the code on CodePen: Open <html> ...

Troubleshooting the malfunctioning of the edit record feature in Python Django when using Jquery

Scenario: My HTML table displays data for a specific user with delete and edit buttons next to each row. While the delete button functions correctly, clicking the edit button does not trigger any action despite following a similar approach. This snippet o ...

Issue: No default template engine specified and no file extension provided. (Using Express framework)

While I came across numerous questions with a similar title, they only provided me with partial help and did not completely resolve the error that plagued me. Just to provide some context, I had created a file named listing.js as a tool for running node c ...

The requested resource at http://localhost/Grafica/%7Bd.icon%7D/ was not found (Error 404)

Creating a tooltip in a weather chart, I want to display an image of the sky condition. Below is the HTML code: <div id="tooltip"> <table class="table table-condensed"> <tr><th>Time (local)</th><th data-text="d ...

Tips for effectively making REST requests from a ReactJS + Redux application?

I'm currently working on a project using ReactJS and Redux, incorporating Express and Webpack as well. I have successfully set up an API and now need to figure out how to perform CRUD operations (GET, POST, PUT, DELETE) from the client-side. Could so ...

Having trouble clicking or interacting with JavaScript using Selenium and Python

Issue: Unable to interact with elements on a specific webpage after opening a new tab. Using WebDriver Chrome. I can successfully navigate the initial webpage until I click a link that opens a new tab, at which point I am unable to perform any actions. ...

Vue.js component fails to load $refs

One of my Vue.js components features a modal view with various embedded references. <template> <div> <b-modal ref="modalDialog" > <b-row> <!-- document --> <b-col> &l ...

Is there a PHP AJAX datagrid solution available for batch updating multiple rows, such as implementing a

Currently seeking an AJAX solution for searching and filtering within a table (referred to as 'products'), allowing for the selection of multiple rows or "all matching results" and tagging them with taxonomies from another table. I have not been ...

Is there a feature similar to Google/YouTube Insight called "Interactive PNGs"?

Recently, I have been exploring the YouTube Insight feature and I am intrigued by how their chart PNGs are generated. When you view the statistics for a video, the information is presented in interactive PNG images. These images seem to be entirely compos ...

Send various pieces of information using Jquery/Ajax

I have encountered a challenge with my script - it currently only sends one value to the requested URL, but I now need it to handle two values. Unfortunately, I haven't been able to figure out how to do this. Each checkbox on the page is paired with ...

Encountering a formatting issue in a C# project while attempting to click the insert button

I have encountered a problem while developing a standalone application in C# - an error pops up when trying to insert data by clicking the button. Can anyone assist me in resolving this issue? Here is the code snippet causing the trouble: try { ...

The click function operates only once

Here are two simple JavaScript functions: CTCC.Transactions.PieceRecuClick = function (source) { $(".chk input[type='checkbox']").attr('checked', true); } CTCC.Transactions.PieceNonRecuClick = function (source) { $(".chk input ...