how to post a model to controller in MVC using ajax

how to post a model to controller in MVC using ajax

samwsamw Posts: 15Questions: 7Answers: 0

I have a datatable which I successfully load data to from a controller using type:GET. then I also have 6 text boxes that allows a user to enter criteria and click a button "Search" to filter the datatable. When a user clicks the Search button how do pass model/object containing the six values entered to the controller? The values in model are all blank when it reaches the controller?

Here's my code:

var employeeID = $('#EmployeeID').val();
var lastName = $('#LastName').val();
var firstName = $('#FirstName').val();
var city = $('#City').val();
var state = $('#State').val();
var zipCode = $('#ZipCode').val();

    var viewModel = {
        EmployeeID: employeeID,
        LastName: lastName,
        FirstName: firstName,
        City: city,
        State: state,
        ZipCode: zipCode
    }

     $('#EmployeeTable').DataTable({

        "ajax": {
            "url": "Employee/SearchEmployees",
            "datatype": "json",
            "serverSide": true,
            "type": "POST",
            "contentType": "application/json charset=utf-8",
            "data": JSON.stringify(viewModel)

        },

        "columns": [
            { data: "EmployeeID", width: "10%" },
            { data: "LastName", width: "20%" },
            { data: "FirstName", width: "20%" },
            { data: "City", width: "20%" },
            { data: "State", width: "10%" },
            { data: "Zipcode", width: "20%" }
        ]

    });

any questions just let me know
thanks

Answers

  • kthorngrenkthorngren Posts: 20,277Questions: 26Answers: 4,765

    Sounds like you will want to use ajax.data as a function. There are a few examples in the docs.

    Kevin

  • samwsamw Posts: 15Questions: 7Answers: 0

    so I got it work, just needed to tweak my code a little bit; I was able to pass my viewmodel to my controller without having to use the function JSON.stringify()

    var viewModel = {

    EmployeeID: employeeID,
    LastName: lastName,
    FirstName: firstName,
    City: city,
    State: state,
    ZipCode: zipCode
    

    }

    $('#EmployeeTable').DataTable({

    "ajax": {
        "url": "/Employee/SearchEmployees",
        "datatype": "json",
        "serverSide": true,
        "type": "POST",
        "data": viewModel
    },
    
    
    "columns": [
        { data: "EmployeeID", width: "10%" },
        { data: "LastName", width: "20%" },
        { data: "FirstName", width: "20%" },
        { data: "City", width: "20%" },
        { data: "State", width: "10%" },
        { data: "Zipcode", width: "20%" }
    ]
    

    });

This discussion has been closed.