【问题标题】:How to pass Ajax Json object to the Controller Class in .Net Core?如何将 Ajax Json 对象传递给 .Net Core 中的控制器类?
【发布时间】:2017-08-22 20:48:28
【问题描述】:

我们正在尝试向我们的 Core Web API 发出 Ajax 请求,并将 data Json 结果返回到 Controller 以进行进一步处理,其中包括 Json 对象结果的反序列化,Ajax 请求工作正常,我们能够在data中获取所需的Json数据。

这里的任何人都可以建议实现这一目标的更改或替代方案吗?

查看(Ajax 请求)

@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");
}

更新:

我已经尝试过@J 给出的解决方案。 Doe,但仍然无法获得结果集。请检查屏幕截图和下面的代码..

Ajax 请求:

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);
    }
});
}

类属性:

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

这是动作结果控制器:

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

错误快照:

enter image description here

【问题讨论】:

    标签: ajax asp.net-core asp.net-core-webapi


    【解决方案1】:

    我们正在尝试

    你好苏联sojuz!

    但回到问题 - 两个月前,我在 GitHub 上使用 .Net Core 的 ajax 创建了示例 - https://github.com/CShepartd/ASP.Net_Core_-_Ajax_Example

    简而言之:

    对控制器中的对象进行操作:

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

    下一个视图发送 name1 和 name2 以采取行动

    $('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) {
                        //...
                    }
                });
            });
    

    【讨论】:

      【解决方案2】:

      1) 添加 [FromBody] 您要返回的控制器。这将使控制器期待一个 JSON 对象。

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

      2) 如果这不起作用,您没有发布正确的 json 对象/您没有发布 json 对象,请使用 console.dir(EventJson); 检查您在浏览器控制台中传递的对象。

      3) 如何在JS中创建JSON对象:https://www.w3schools.com/js/js_json_stringify.asp

      【讨论】:

        猜你喜欢
        • 2013-01-29
        • 1970-01-01
        • 2017-01-11
        • 1970-01-01
        • 2018-05-02
        • 1970-01-01
        • 1970-01-01
        • 2011-09-05
        • 1970-01-01
        相关资源
        最近更新 更多