amiryami
amiryami

Reputation: 3

how to send json data to mvc controller

my ajax code is :

  $.ajax({
            url: "/Dashboard/filter",
            data: jsonData,
            traditional: true,
            contentType: 'application/json',
            dataType: 'json',
            type: "POST",
            success: function (data) {
                console.error(data);

            },
            error: function (error) {
                console.error(error);
            }
        });

and my controller action :

    [HttpPost]
    public JsonResult filter(Utility.FJson filterjson)
    {

        return Json(new { });
    }

in Utility class:

 public class FilterJson
    {
        public string IdField { get; set; }
        public string NameField { get; set; }
        public int Check { get; set; }
        public string SFilter { get; set; }
        public string TFilter { get; set; }
    }
    public class FJson
    {
        public List<FilterJson> filter { get; set; }

    }

error massage is :

POST http://localhost:38064/Dashboard/filter 500 (Internal Server Error)

i want send json to mvc controller. if JSON.stringify(jsonData) in send time .in controller filterjson variable is NULL

Upvotes: 0

Views: 69

Answers (1)

Reza Jenabi
Reza Jenabi

Reputation: 4319

You can use the following code to send and receive Json in the form of a class

Ajax code is:

 var data = "{filter :[{IdField: '2', NameField: 'filter item', Check: 1 , SFilter: 'filter search' , TFilter: 'filter text'}]}";
    $.ajax({
        url: '/home/filter',
        dataType: 'json',
        type: 'POST',
        data: data,
        contentType: 'application/json; charset=utf-8',
        success: function (data) {
            alert(data);
        },
        error: function () {
            alert("error");
        }
    });

Class:

public class FilterJson
{
    public string IdField { get; set; }
    public string NameField { get; set; }
    public int Check { get; set; }
    public string SFilter { get; set; }
    public string TFilter { get; set; }
}
public class FJson
{
    public List<FilterJson> filter { get; set; }

}

Controller action is:

[HttpPost]
public JsonResult filter(FJson filterjson)
{

    return Json(new { });
}

Upvotes: 1

Related Questions