【问题标题】:Passing JSON to WebApi in MVC5在 MVC 5 中将 JSON 传递给 Web Api
【发布时间】:2015-05-30 06:53:02
【问题描述】:

我在将 json 数组从 jquery 传递到我的 mvc5 项目中的 webapi 时遇到语法问题。

以下是我的代码:-

C#代码:-

//获取实例

    // GET: api/PostDatas
    public IQueryable<PostData> GetPostDatas()
    {
        return db.PostDatas;
    }

//POST 实例

     // POST: api/PostDatas
    [ResponseType(typeof(PostData))]
    public IHttpActionResult PostPostData(PostData postData)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        db.PostDatas.Add(postData);
        db.SaveChanges();

        return CreatedAtRoute("DefaultApi", new { id = postData.postDataID }, postData);
    }

jQuery

  <script>
   function fnpostdata() {
    var model = {
        "userid": "01",
        "Description": "Desc",
        "photoid": "03"
    };
     $.ajax({
        type: "POST",
        dataType: "json",
        contentType: "application/json",
        url: "/api/PostDatas/",
        data: model,
        success: function (data) {
            alert('success');
        },
        error: function (error) {
            jsonValue = jQuery.parseJSON(error.responseText);
            jError('An error has occurred while saving the new part source: ' + jsonValue, { TimeShown: 3000 });
         }
      });
  }
     </script>

我无法使用 jquery 将数据发送到我的 c# 控制器,只需要了解语法。谢谢。

【问题讨论】:

  • 你有什么错误吗?
  • 虽然没有错误,但.. 实际上,我的数据没有发布到我的 c# 控制器中。
  • //GET INSTANCE 正在从数据库中检索数据,但是 //POST INSTANCE 在将数据发布到数据库时遇到了一些问题,需要帮助理解他的语法..

标签: c# jquery json asp.net-web-api


【解决方案1】:

检查代码中的以下内容: 1) 方法属性[HttpPost] 2) [FromBody] 用于输入模型 3) 检查 PostData 类,它应该包含 userid、Description 和 photoid 的公共属性,变量名区分大小写。

主要将您的 AJAX 请求代码更改为:

function fnpostdata() {
    var model = {
        "userid": "01",
        "Description": "Desc",
        "photoid": "03"
    };
     $.ajax({
        type: "POST",
        dataType: "json",
        contentType: "application/json",
        url: "/api/PostDatas/",
        data: JSON.stringify(model), //i have added JSON.stringify here
        success: function (data) {
            alert('success');
        },
        error: function (error) {
            jsonValue = jQuery.parseJSON(error.responseText);
            jError('An error has occurred while saving the new part source: ' + jsonValue, { TimeShown: 3000 });
         }
      });
  }

请告诉我,这对你有用吗?

【讨论】:

    【解决方案2】:

    我在上一个项目的参数中包含了[FromBody]。 像这样的:

    [HttpPost]
    public IHttpActionResult Register([FromBody]PostData postData)
    {
         // some codes here
    }
    

    我能够从该符号中读取 JSON 数据。

    【讨论】:

    • 我给出的上述代码..没有给出任何错误,也没有将值传递给我的数据库..但有什么解决方案..?尝试了您的代码,但没有成功:(
    • 你可以尝试在 fiddler 中测试它,也许它可以帮助追踪问题
    猜你喜欢
    • 2013-01-15
    • 1970-01-01
    • 2021-12-31
    • 1970-01-01
    • 2020-06-26
    • 2012-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多