"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

Can you identify the selected item on the menu?

My goal is to highlight the menu item for the current page by adding a "current" class. I've tried several code snippets from this website, but most of them didn't work as expected. The code I'm currently using almost works, but it has a sma ...

Hiding a pop-up element and updating the state to False when clicking anywhere outside the element in the background

Presented here is my Search.js component. class Search extends Component { state = { doctors: [], showTab: false } openTab = () => { this.setState({showTab: true}); console.log('openTab state', this ...

Is there a way to incorporate CSS or tables when converting HTML to PDF using JavaScript?

While working on a project, I successfully converted an HTML file into a PDF. However, the output did not display the CSS design. Can anyone provide suggestions on how to include CSS design in the PDF file? Below is the JavaScript function code: $(funct ...

The ASP.NET MVC3 form collection registers as 0 when performing a jQuery ajax post

I'm currently developing a project on ASP.NET MVC3. My current challenge involves POSTing to a method that should return a set of data using the jQuery.ajax api. However, upon handling the request on the server, I noticed that the form collection&apo ...

Leveraging the power of Angular to send the contents of a div via email

I have a div element with a specific class name and I am currently exploring ways to extract the rendered components of that div as text in order to include it in the body of an email. I have tried various methods such as using classes and ng-model, but so ...

Guide on utilizing the disable feature in SortableJS for a Vue project

I have successfully implemented the draggable effect on my el table using element-ui-el-table-draggable and it's working perfectly. Now, I am looking to incorporate the disable option from SortableJS, but I'm unsure how to integrate these two fu ...

I'm sorry, there seems to be a JSON error. The syntax is incorrect and it

I am facing a problem where I encounter an error when trying to post a JSON object. The error message reads: SyntaxError: JSON.parse: unexpected character Here is my JavaScript object: var $arr_data = { title: '', category: &apo ...

Click on the radio button to delete all selected entries in the option dropdown

After spending the entire day trying to find a solution, I am still struggling with a simple task - how do I clear all selections from a group of select option drop downs at once without removing them? I want the selections to revert back to their default ...

Resolving TypeError: matchesSelector method is not recognized within React component

I am currently integrating masonry-layout from the official website to create a masonry grid within my component. However, I encountered an issue where clicking on a rendered element triggers the error message TypeError: matchesSelector is not a function. ...

AngularJS $scope variable can be initialized only once using an HTTP GET request

I'm facing an issue with fetching data from an API in a separate AngularJS application. There's a button that triggers the retrieval of data from the API. Upon clicking, it executes the $scope.getApiData function, which is connected to $scope.pr ...

Exploring the features of NextJS version 13 with the benefits

Starting from the 13th step, SSR is utilized by default and in order to opt for client side rendering you must specify it at the top like so: 'use client' Currently, my setup involves TypeScript and styled-component integration. Take a look at ...

Discover and update values in JSON using JavaScript

Currently, I am working on generating graphs using d3.js with a JSON file as the input. My main challenge lies in parsing the date and time format for the x-axis. Below is the code snippet that I have attempted: d3.json('data/fake_users11.json', ...

Utilizing repl.it for a database in Discord.js

I've created a database script on repl.it and it seems to be functioning properly. However, I keep encountering null values in the users' database. Here's my code snippet: client.on("message", async (message) => { if (messag ...

Attempt to write an rspec test for the retrieval method using ajax

Looking to create an rspec test for the get method via ajax. The current response is 302, but expecting 200. The same results are obtained when testing the Post method. user_pages_spec.rb require 'spec_helper' describe "ProgectPage" do subj ...

Implementing AJAX, PHP, and MYSQL to dynamically fill text boxes with data when an item is selected

How can I capture user input in a text box based on their selection of a place? I have attempted to achieve this functionality with the code below, but it's not working as expected. Can someone offer guidance on how to fix this issue? This is what I& ...

Ensuring the presence of Objects/Functions in different browsers using javascript

I am seeking advice on the best practices for testing object existence for cross-browser compatibility. There are numerous methods available for testing whether an object/function/attribute exists. While I could utilize jQuery or another library, my prefe ...

Is it possible to activate the jQuery .click() function for a button with specific text?

Here's a dilemma I'm facing: $('.add_to_cart span:contains("Choose a Size")').click(function() { console.log("it has been clicked") }); <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></s ...

To enable RTL in TextField, please note that the JssProvider is only available in "react-jss/src/JssProvider" and not in "react-jss/lib/JssProvider"

Seeking help to convert LTR to RTL in the following code: <TextField id="date" label="EmployeeDate" type="date" onChange= ...

Executing MySQL queries synchronously in Node.js

When working with NodeJS and mysql2 to save data in a database, there are times when I need to perform database saves synchronously. An example of this is below: if(rent.client.id === 0){ //Save client connection.query('INSERT INTO clients (n ...

Loading an Angular2 app is made possible by ensuring that it is only initiated when a DOM element is detected

In my main.ts file, the code below is functioning perfectly: import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; import { AppModule } from './app.module'; platformBrowserDynamic().bootstrapModule(AppModule); H ...