0

We are trying to make a Ajax request to our Core Web API and get the data Json result back to the Controller for further processing, Which include Deserialization of the Json object result, Ajax request is working fine and we are able to get the required Json data in data.

Can anyone here please advise the changes or the alternatives to achieve this?

View (Ajax Request)

@section scripts
{
<script type="text/javascript">
    $(document).ready(function () {
    GetEventDetails('@Url.Content("~/")');
    });



    function GetEventDetails(contextRoot) {
    $.ajax({
    type: "GET",
    url: contextRoot + "api/EventsAPI",
    dataType: "json",
    success: function (data) {
        debugger;
        var datavalue = data;
        contentType: "application/json";
        //Send data to controller ???
        console.log(data);
    },
    error: function (xhr) {
        alert(xhr.responseText);
    }
    });
    }
</script>
}

Controller.cs

public ActionResult Index()
{    
    /*Do all stuff before returning view 
    1. Get Json Data from Ajax request
    2. Deserialize the obtained Json Data
    3. return to view
    */
    return View("Index");
}

Update:

I have tried the solution given by @J. Doe, but still unable to get the result set. Please check the screenshot and below code..

Ajax Request:

function GetEventDetails(contextRoot) {        
        $.ajax({
            type: "GET",
            url: contextRoot + "api/EventsAPI",
            dataType: "json",
            success: function (data) {
                debugger;
                var datavalue = data;
                contentType: "application/json; charset=utf-8";                 
                console.log(data);
                var EventJson = data;
                console.log(EventJson);
                $.ajax({             
                    type: "POST",
                    url: "@Url.Action("Index")",
                    dataType: "json",
                    data: EventJson,
                    contentType: "application/json; charset=utf-8",                        
                        //data: EventJson,                       
                    success: function (data) {
                        alert(data.responseText);
                        console.log('Data received: ');
                        console.log(data.responseText);                           
                    },
                    failure: function (errMsg) {
                        console.log(errMsg);
                }
            });
    },
    error: function (xhr) {
        alert(xhr.responseText);
    }
});
}

Class Properties:

public class RootObject
{
    public Embedded _embedded { get; set; }
    public Links _links { get; set; }
    public Page page { get; set; }
}

Here is Action Result Controller:

public ActionResult Index(RootObject model)
{
    if (model != null)
    {
        return Json("Success");
    }
    else
    {
        return Json("An Error Has occoured");
    }
    //return View("Index");
}

Error Snapshot:

enter image description here

2 Answers 2

1

1) Add [FromBody] the controller you are returning to. This will make the controller expect a JSON object.

[HttpPost]
public ActionResult Index([FromBody]RootObject model)
    {
        if (model != null)
        {
            return Json("Success");
        }
        else
        {
            return Json("An Error Has occoured");
        }
        //return View("Index");
    }

2) If this doesn't work you are not posting a correct json object/you are not posting a json object use console.dir(EventJson); to inspect the object you are passing in the console of the browser.

3) How to create a JSON object in JS: https://www.w3schools.com/js/js_json_stringify.asp

Sign up to request clarification or add additional context in comments.

Comments

0

We are trying

Hello soviet sojuz!

But back to question - A 2 months ago i created sample on GitHub with ajax with .Net Core - https://github.com/CShepartd/ASP.Net_Core_-_Ajax_Example

In short:

Make action with objects in controller:

    public IActionResult Ajax(string name1, string name2)
    {
        return View();
    }

Next in view send name1 and name2 to action

$('form').submit(function(event) {
            event.preventDefault();
            var data = {
                name1: $("input[name='name1']", this).val(),
                name2: $("input[name='name2']",this).val()
            };

            $.ajax({
                type: 'POST',
                url: '/Home/Ajax',
                dataType: 'json',
                data: data,
                success: function(response) {
                    alert(response);
                    console.log('Data received: ');
                    console.log(response);
                },
                failure: function(response) {
                    //...
                },
                error: function(response) {
                    //...
                }
            });
        });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.