【发布时间】:2019-01-11 23:14:50
【问题描述】:
我创建了一个表单,用户通过该表单输入数据,按下提交按钮后,数据作为 PUT Ajax 请求传递。问题是它实际上并没有作为 PUT 请求传递,而是在调查后发现它实际上是作为 GET 请求传递的,数据是查询字符串,而不是在 PUT 请求的主体参数中发送.
我尝试通过 firefox 调试 jquery 代码,但在提交调试器时不会暂停以跳过页面,而是发送一个 GET 请求,其中查询字符串作为 ajax 请求中 vm 变量中提供的数据传递.这是我的 HTML.cs 表单:
@model Auth.ViewModels.NewCustomerViewModel
@{
ViewBag.Title = "New";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>New Customer</h2>
<form id="idk">
@Html.ValidationSummary(true, "Please fix the following errors: ")
<div class="form-group">
@Html.LabelFor(m => m.Customer.Name)
@Html.TextBoxFor(m => m.Customer.Name, new { @class = "form-control", @id = "customername" })
@Html.ValidationMessageFor(m => m.Customer.Name)
</div>
<div class="form-group">
@Html.LabelFor(m => m.Customer.MembershipTypeId)
@Html.DropDownListFor(m => m.Customer.MembershipTypeId, new SelectList(Model.MembershipTypes, "Id", "MembershipName"), "Select Membership Type", new { @class = "form-control", @id = "membershipname" })
@Html.ValidationMessageFor(m => m.Customer.MembershipTypeId)
</div>
<div class="form-group">
@Html.LabelFor(m => m.Customer.BirthDate)
@Html.TextBoxFor(m => m.Customer.BirthDate, "{0:d MMM yyyy}", new { @class = "form-control", @id = "birthdate" })
@Html.ValidationMessageFor(m => m.Customer.BirthDate)
</div>
<div class="checkbox">
<label>
@Html.CheckBoxFor(m => m.Customer.IsSubscribedToNewsletter, new { @id = "subscribename" }) Subscribe to Newsletter?
</label>
</div>
<div class="checkbox">
<label>
@Html.CheckBoxFor(m => m.Customer.Irresponsible, new { @id = "irresponsiblename" }) Delinquent Person
</label>
</div>
@Html.HiddenFor(m => m.Customer.Id, new { @id = "id" })
@Html.AntiForgeryToken()
<button type="submit" id="submit" class="btn btn-primary">Save</button>
</form>
@section scripts {
@Scripts.Render("~/bundles/jqueryval")
<script>
$(document).ready(function () {
$("#submit").on("click",function (event) {
var vm = { id: $("#id").val(), Name: $("#customername").val(), IsSubscribedToNewsLetter: $("#subscribename").val(), MembershipTypeId: $("#membershipname").val(), BirthDate: $("#birthdate").val(), Irresponsible: $("#irresponsiblename").val(), Id: $("#id").val() };
$.ajax({
url: "/api/Customers/UpdateCustomer",
method: "PUT",
data: {vm },
success: function () {
Location("customers/Index");
//button.parents("tr").remove();
}
});
});
});
</script>
}
这里是处理这个 PUT 请求的后端:
[HttpPut]
public IHttpActionResult UpdateCustomer(int id, CustomerDto customerDto)
{
if (!ModelState.IsValid)
return BadRequest();
var customerInDb = _context.Customer.SingleOrDefault(c => c.Id == id);
if (customerInDb == null)
return NotFound();
Mapper.Map<CustomerDto, Customer>(customerDto, customerInDb);
_context.SaveChanges();
return Ok();
}
我只是不知道为什么它没有作为 PUT 请求传递给后端,以及为什么数据作为查询字符串参数传递。我的期望是它将通过 PUT 请求传递数据并更新数据库中的各个字段
【问题讨论】:
标签: jquery asp.net asp.net-mvc asp.net-ajax