我使用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");
}
});
};
在调试模式下,它显示:
我不明白我错在哪里。
答案 0 :(得分:2)
这里有2个问题
companyInformation
期待来自Uri,但之后您将在请求正文中发送数据。application/json
有几种方法可以解决这个问题,这就是我要做的。首先,从您[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");
}
});