Home > Mobile >  ajax call not send the data to controller
ajax call not send the data to controller

Time:02-02

I trying to pass data from view to controller using ajax call but I receive null in the controller.In action my parameter is becoming null.

My View:

$(document).on('click','.btnsubmit', function (e) {
        e.preventDefault();
        var id = parseInt($(this).attr("id"));
        var value=$("#txt_" id).val();
        debugger
        $.ajax({
            url: "/Home/AddResult",
            type :"POST",
            contentType: "application/json",
            async:false,
            
            data: JSON.stringify({"id":id,"value":value}),
            
                success: function (data) {
                alert("Result Saved");
                console.log(data.result);


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

My Controller:

 public IActionResult AddResult(int id,string value)
        {
            if(ModelState.IsValid)
            {
                test.Update(id, value);
            }
            return Json(new { result = true });
        }

CodePudding user response:

You can create a model contains these parameters then use [FromBody]

public class TestA
        {
            public int id { get; set; }
            public string value { get; set; }

        }

enter image description here

Or

You can just delete contentType: "application/json", , then change

data: {"id":id,"value":value}

Now you can receive data normally.

  • Related