为什么我在web api的put请求中得到了我的模型属性null?

时间:2013-04-26 17:03:28

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

我使用JQuery和Ajax从我的View向Web API控制器发送PUT请求。它击中了我的web api控制器,但我的模型属性为空。

这是我的控制器代码:

public HttpResponseMessage Put(Int64 id, 
           [FromUri] CompanyInformation companyInformation) {
  try {
    if (ModelState.IsValid) {
      if (IsUniq(companyInformation.Name)) {
        _smUnitOfWork.CompanyInformations.Update(companyInformation);
        _smUnitOfWork.Save();
        return Request.CreateResponse(HttpStatusCode.OK, 
           string.Format(Messagess.UpdatedSuccess, 
                         companyInformation.Name));
      }
    }
    return Request.CreateResponse(HttpStatusCode.BadRequest, 
           string.Format(Messagess.AlreadyExist, 
                         companyInformation.Name, TypeNameMessages));
  } catch (Exception) {
    return Request.CreateResponse(HttpStatusCode.BadRequest, 
                                  Messagess.UnbaleToProcess);
  }
}

我的观点是:

  <div id="companySetup">
   @using (Html.BeginForm(null,null, FormMethod.Post, new{id="MyId"}))
   {
    <div>
        <div>
            <h2>Company Setup</h2>
            <ul>
                <li>
                    @Html.LabelFor(x => x.Name)
                    @Html.TextBoxFor(x => x.Name)
                </li>
                <li>
                    @Html.LabelFor(x => x.FirstAddress)
                    @Html.TextAreaFor(x => x.FirstAddress)
                </li>
                <li>@Html.LabelFor(x => x.SecondAddess)
                    @Html.TextAreaFor(x => x.SecondAddess)
                </li>
                <li>
                    @Html.LabelFor(x => x.ContractDeatils)
                    @Html.TextAreaFor(x => x.ContractDeatils)
                </li>
                <li>
                    @Html.LabelFor(x => x.Email)
                    @Html.TextBoxFor(x => x.Email, new { type = "email" })
                </li>
                <li>
                    @Html.LabelFor(x => x.Web)
                    @Html.TextBoxFor(x => x.Web)
                </li>
            </ul>
            @Html.HiddenFor(x => x.Id)
        </div>
        <div class="buttonAlinment">
            <input type="submit" value="Reset" />
            <input type="submit" value="Update" />
        </div>
    </div>
}

我的JavaScript是:

var updateCompanyInfo = function () {
var companyInformation = {
    "Name": $("#Name").val(),
    "FirstAddress": $("#FirstAddress").val(),
    "SecondAddess": $("#SecondAddess").val(),
    "ContractDeatils": $("#ContractDeatils").val(),
    "Web": $("#Web").val(),
    "Id": $("#Id").val(),
    "Email": $("#Email").val(),
};

$.ajax({
    url: '/api/CompanyInformation/' + $('#Id').val(),
    type: 'PUT',
    contentType: "application/json; charset=utf-8",
    data: { companyInformation: companyInformation },
    success: function (result) {
        alert("Done");
    }
});

};

在调试模式下,它显示: enter image description here

我不明白我错在哪里。

1 个答案:

答案 0 :(得分:2)

这里有2个问题

  1. 您的companyInformation期待来自Uri,但之后您将在请求正文中发送数据。
  2. 目前正文采用urlencoded内容格式,但您指定的数据类型位于application/json
  3. 有几种方法可以解决这个问题,这就是我要做的。首先,从您[FromUrl]方法的companyInformation参数中删除PUT

     public HttpResponseMessage Put(Int64 id, CompanyInformation companyInformation) 
     {
         ...
     }
    

    然后使用JSON.stringify(...)将数据转换为客户端的JSON:

    $.ajax({
        url: '/api/CompanyInformation/' + $('#Id').val(),
        type: 'PUT',
         contentType: "application/json; charset=utf-8",
         data: JSON.stringify(companyInformation),
         success: function (result) {
             alert("Done");
         }
     });