簡體   English   中英

在MVC5中將JSON傳遞給WebApi

[英]Passing JSON to WebApi in MVC5

我面臨語法問題,將jQuery數組從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#控制器,僅需要了解語法。 謝謝 。

檢查代碼中的以下內容: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 });
         }
      });
  }

請讓我知道,這對您有用嗎?

我在上一個項目的參數中包含了[FromBody] 像這樣:

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

我能夠從該表示法讀取JSON數據。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM