How To Send Sequence of Specific Object To Mvc Core Action through jquery ajax

437 Views Asked by At

I was created a function that is responsible to created and sending a json :

function Send(op) {
    var tr = $(op).parents('tr');
        var item = [];

        $(tr).find("td").each(function () {
            item.push($(this).find("input").prop("name") + '":' + '"' + $(this).find("input").val());
        });
        var myJsonString = JSON.stringify(item);

        $.ajax({
            url: '/Home/Edit',
            data: myJsonString,
            type:'post',
            contentType: 'application/json; charset=utf-8',
            cache: false,
            success: function () {
                alert('send is okay')
            }
        });
}

to an IActionResult :

   [HttpPost]
    public ActionResult Edit([FromBody]Hazine hazine)
    {
        return View();
    }

but it (Edit Action) cant get object from jquery. so this Action Invoked Succcefully but with null hazine!

a json created which I get from console.log is :

["id\":\"4","undefined\":\"undefined","undefined\":\"undefined","HazineType1\":\"1","HazineType2\":\"1","SendDate\":\"5","ProjectId\":\"1","Mablagh\":\"1","MablaghPaid\":\"1","HazineDate\":\"1","HazineDateLong\":\"1","HazineTitle\":\"11111","HazineComment\":\"1","ForoshgahName\":\"1","PayLastDate\":\"1","PayDateLong\":\"111111111","UniqueId\":\"1111","SaveDate\":\"8888","SaveDateLong\":\"888","SendDate\":\"5","SendDateLong\":\"5"]

what was wrong?

2

There are 2 best solutions below

0
AudioBubble On BEST ANSWER
 public class Hazine:TableBase
{


    [Key]
    public string UniqueId { get; set; }



    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]

    public int HazineId { get; set; }


    public int HazineType1 { get; set; } // check paid , check




    public int ProjectId { get; set; }



    public int Mablagh { get; set; }




    public int MablaghPaid { get; set; }




    [StringLength(150)]
    public string HazineDate { get; set; }




    public long HazineDateLong { get; set; }



    [StringLength(150)]
    public string HazineTitle { get; set; }




    [StringLength(350)]
    public string HazineComment { get; set; }



    [StringLength(150)]
    public string ForoshgahName { get; set; }




    [StringLength(150)]
    public string PayLastDate { get; set; }




    [StringLength(150)]
    public long PayDateLong { get; set; }               

}

    public class TableBase
{
    [NotMapped]
    public bool isModified { get; set; }



    [StringLength(150)]
    public string SaveDate { get; set; }



    public long SaveDateLong { get; set; }



    [StringLength(150)]
    public string SendDate { get; set; }




    public long SendDateLong { get; set; }

}

Console Log:

{"HazineId":"4","UniqueId":"1111","HazineType1":"1","HazineType2":"1","SendDate":"5","ProjectId":"1","Mablagh":"1","MablaghPaid":"1","HazineDate":"1","HazineDateLong":"1","HazineTitle":"11111","HazineComment":"1","ForoshgahName":"1","PayLastDate":"1","PayDateLong":"111111111","SaveDate":"8888","SaveDateLong":"888","SendDateLong":"5"}

It Work:

   [HttpPost]
    public IActionResult Edit([FromBody]Object data)
    {
       Hazine hazineJson =JsonConvert.DeserializeObject<Hazine>(data.ToString());

        hazine.Update(hazineJson);
        return View();
    }

It not work:

[HttpPost]
    public IActionResult Edit([FromBody]Hazine data)
    {

        hazine.Update(data);
        return View();
    }

in second function cant call and err 500 occure

enter image description here

13
Edward On

For sending object to Controller with FromBody, the json string should map the parameter.

For your action, it accept an object, but for your json, you are sending a collection object.

Try something like below:

function Send(op) {
    var tr = $(op).closest('tr');
    var item = {};

    $(tr).find("td").each(function () {
        item[$(this).find("input").prop("name")] = $(this).find("input").val();                    
        });
        var myJsonString = JSON.stringify(item);
    console.log(myJsonString);
        $.ajax({
            url: '/Home/Edit',
            data: myJsonString,
            type:'post',
            contentType: 'application/json; charset=utf-8',
            cache: false,
            success: function () {
                alert('send is okay')
            }
        });
}

If you are using .net core 3.0, you also need to configure the json serializer by installing Microsoft.AspNetCore.Mvc.NewtonsoftJson and configure it like

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllersWithViews().AddNewtonsoftJson();
}