Home > Back-end >  Received NULL Object in Controller when send request from view ( Ajax) even I use [FromBody] C#
Received NULL Object in Controller when send request from view ( Ajax) even I use [FromBody] C#

Time:03-11

Model:

public class From
        {
            public DateTime from { get; set; }
            public DateTime to { get; set; }

        }

Controller:

public MediaViewModel DashboardMediaByDate([FromBody] From y)
        { // some logic }

View:

<script>

    $(function () {
        // Get value on button click and show alert
        $("#myBtn").click(function () {
            var from =  {
                from: $("#from").val(), to: $("#to").val()
            };
            alert(from.from);
            var y = JSON.stringify(from);

            $.ajax({
                type: "POST",
                data: y,
                dataType: 'json',

                url: "/Queues/DashboardMediaByDate",
                contentType: "application/json"
            }).done(function (res) {
                alert(res);
            });
        });

    });
   

</script>

When I debug the request from browser :

Request Header Payload

What I received in Controller:

Method Parameter
How can I send the object to controller from view model ?

Thanks in advance,

CodePudding user response:

You can use the following AJAX call to get your data as required:

AJAX:

<script>
    $(function () {
        // Get value on button click and show alert
        $("#myBtn").click(function () {
        
            var from =  {
                from: $("#from").val(), to: $("#to").val()
            };
            
            alert(from.from);
            
            $.ajax({
                type: "POST",
                data: {'json': JSON.stringify(from)},
                dataType: 'json',
                url: "/Queues/DashboardMediaByDate"
            }).done(function (res) {
                alert(res);
            });
        });
    });
   
</script>

And your Controller method:

using System.Web.Script.Serialization;


[HttpPost]
public JsonResult DashboardMediaByDate(string json)
{
        MediaViewModel myModel = new MediaViewModel();
        var serializer = new JavaScriptSerializer();
        dynamic jsondata = serializer.Deserialize(json, typeof(object));

        //Get your variables here from AJAX call
        var from  = Convert.ToDateTime(jsondata["from"]);
        var to  = Convert.ToDateTime(jsondata["to"]);
        
        //Your logic

        return Json(new {myModel=myModel});
}

Changes from your original call:

  1. Removed contentType from your AJAX call
  2. Added [HttpPost] attribute on your Controller method
  3. Removed [FromBody] attribute to get your data as a JSON string
  4. Changed your data to send a JSON string instead of a Model

Once you get your data as a JSON string, you can de-serialize it your Model structure as required. I usually use this method when my Model does not have many properties.

You are using AJAX for your functionality which is generally used to update a portion of the page without reloading the entire page. If you want to redirect in the POST method from your Controller with a Model, then don't use ajax for your purpose. Alternatively if you know what to add to the view you return then handle the success callback and update the DOM.

You can access the above Model in your success method inside your AJAX like this:

success: function(data) {
    //Get your model here
    console.log(data.myModel);
}
  • Related