Bluemarble
Bluemarble

Reputation: 2059

Multiple Ajax Call parameters all coming as null in .Net Core Controller

I know this question has been asked several times here, but none of the answers are working for me. I am trying everything since last 3 hours.

Requirement is simple: Call a .Net Core 2.1 Controller method from View using JQuery. Pass 3 parameters to controller.

My jQuery:

function EmpSubmit() {
    var EmpName = $('#txtEmpName').val();
    var EmpDesignation = $('#txtDesignation').val();
    var EmpCity = $('#txtCity').val();

    // ajax call to create new employee

    var data1 = '{"EmpName": "' + EmpName + '", "EmpDesignation" : "' + EmpDesignation + '", "EmpCity" : "' + EmpCity + '"}';
    
    $.ajax({
        url: '@Url.Content("~/Employee/CreateViaModal/")',
        dataType: 'json',
        type: 'POST',
        data: data1,
        contentType: 'application/json',
        success: function (result) {

            $("#EmpCreateModal").modal('hide');
            window.location.reload(true);
        }
    });
}

The Controller:

[HttpPost]
    public IActionResult CreateViaModal(string EmpName, string EmpDesignation, string EmpCity)
    {
        TblEmployee tblEmployee = new TblEmployee();
        tblEmployee.EmpName = EmpName;
        tblEmployee.Designation = EmpDesignation;
        tblEmployee.City = EmpCity;

        _context.Add(tblEmployee);
       _context.SaveChanges();

        return Json(tblEmployee);
    }

The Ajax call is hitting the debugger in the controller successfully, just the parameters are coming as NULL all the time. Not sure what needs to be done here.

Upvotes: 0

Views: 378

Answers (1)

Your code does not work because you are sending a string to your action.

Replace var data1 = '{"EmpName": "' + EmpName + '", "EmpDesignation" : "' + EmpDesignation + '", "EmpCity" : "' + EmpCity + '"}'; with

var data1 = {
    EmpName,
    EmpDesignation,
    EmpCity
}

and in your AJAX request: data: JSON.stringify(data1) instead of data: data1,

After that, create a Employee class:

public class Employee
{
  public string EmpName {get;set;}
  public string EmpDesignation {get;set;}
  public string EmpCity {get;set;}
}

and change your action method to:

public IActionResult CreateViaModal([FromBody]Employee employee)

Upvotes: 1

Related Questions