Jquery Ajax请求作为GET请求而不是PUT请求传递
我创建了一个表单,用户通过该表单输入数据,按下submit按钮后,数据将作为PUT Ajax请求传递。问题在于,它实际上不是作为PUT请求传递的,而是经过调查发现,它实际上是作为GET请求传递的,数据是查询字符串,而不是在PUT请求的主体参数中发送的 我尝试通过firefox调试jquery代码,但在提交时,调试器不会暂停以跨过页面,而是发送一个GET请求,其中查询字符串作为ajax请求中vm变量中提供的数据传递。这是我的HTML.cs表单:Jquery Ajax请求作为GET请求而不是PUT请求传递,jquery,asp.net,asp.net-mvc,asp.net-ajax,Jquery,Asp.net,Asp.net Mvc,Asp.net Ajax,我创建了一个表单,用户通过该表单输入数据,按下submit按钮后,数据将作为PUT Ajax请求传递。问题在于,它实际上不是作为PUT请求传递的,而是经过调查发现,它实际上是作为GET请求传递的,数据是查询字符串,而不是在PUT请求的主体参数中发送的 我尝试通过firefox调试jquery代码,但在提交时,调试器不会暂停以跨过页面,而是发送一个GET请求,其中查询字符串作为ajax请求中vm变量中提供的数据传递。这是我的HTML.cs表单: @model Auth.ViewModels.New
@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>
}
@model Auth.ViewModels.NewCustomerViewModel
@{
ViewBag.Title=“新建”;
Layout=“~/Views/Shared/_Layout.cshtml”;
}
新客户
@ValidationSummary(true,“请修复以下错误:”)
@LabelFor(m=>m.Customer.Name)
@TextBoxFor(m=>m.Customer.Name,新的{@class=“form control”,@id=“customername”})
@Html.ValidationMessageFor(m=>m.Customer.Name)
@LabelFor(m=>m.Customer.MembershipTypeId)
@Html.DropDownListFor(m=>m.Customer.MembershipTypeId,新选择列表(Model.MembershipTypes,“Id”,“MembershipName”),“选择成员类型”,新{@class=“form control”,@Id=“MembershipName”})
@Html.ValidationMessageFor(m=>m.Customer.MembershipTypeId)
@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)
@CheckBoxFor(m=>m.Customer.IsSubscribedToNewsletter,new{@id=“subscribebename”})订阅时事通讯?
@CheckBoxFor(m=>m.Customer.unresponsible,新的{@id=“unresponsiblename”})违法者
@Html.HiddenFor(m=>m.Customer.Id,新的{@Id=“Id”})
@Html.AntiForgeryToken()
拯救
@节脚本{
@Scripts.Render(“~/bundles/jqueryval”)
$(文档).ready(函数(){
$(“#提交”)。在(“单击”)上,功能(事件){
var vm={id:$(“#id”).val(),Name:$(“#customername”).val(),IsSubscribedToNewsLetter:$(“#subscribername”).val(),MembershipTypeId:$(“#membershipname”).val(),生日:$(“#生日”).val(),不负责任的:$(“#不负责任的姓名”).val(),id:$(“#id”).val();
$.ajax({
url:“/api/Customers/UpdateCustomer”,
方法:“放”,
数据:{vm},
成功:函数(){
地点(“客户/索引”);
//按钮。父项(“tr”).remove();
}
});
});
});
}
以下是处理此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();
}
[HttpPut]
公共IHttpActionResult UpdateCustomer(int id,CustomerTo CustomerTo)
{
如果(!ModelState.IsValid)
返回请求();
var customerInDb=_context.Customer.SingleOrDefault(c=>c.Id==Id);
if(customerInDb==null)
返回NotFound();
Map(customerDto,customerInDb);
_SaveChanges();
返回Ok();
}
我只是不知道为什么它不作为PUT请求传递到后端,为什么数据作为查询字符串参数传递。我的期望是它将通过PUT请求传递数据,并更新数据库中的各个字段我猜您的jQuery版本是<1.9。如果是这种情况,您需要使用
类型
而不是方法
,:
类型(默认值:“GET”)类型:字符串方法的别名。你应该使用
如果您使用的是1.9.0之前版本的jQuery,请键入
您通常会以错误的格式发送数据,这会意外地被解释为具有不同参数的另一个方法(该方法从未存在过),或者导致将参数绑定到正确数据类型的数据失败。例如,您正在发送以下数据:
var vm = {
id: 123
};
预期的API端点
GET /account/update-customer/123 // OK 200
// Url encoded. This method expects an integer as parameter but string was passed.
GET /account/update-customer/vm%5Bid%5D=123 // Internal Server Error 500
实际发送的URL
GET /account/update-customer/123 // OK 200
// Url encoded. This method expects an integer as parameter but string was passed.
GET /account/update-customer/vm%5Bid%5D=123 // Internal Server Error 500
因此,如果您需要,请从vm
对象中删除花括号(因为它已经是一个对象),以便HTTP将它们正确地烘焙到URL中,或者让jQuery为您查询数据,并且无需麻烦(您可能应该这样做)
以下是完整的代码片段,以及我的一些重构建议:
您可能已经在这样做了,但是使用它可以在以后的阶段(例如在AJAX调用中)以更易于维护的方式获取API url
从
@LabelFor(m=>m.Customer.Name)
@TextBoxFor(m=>m.Customer.Name,新的{@class=“form control”,@id=“customername”})
@Html.ValidationMessageFor(m=>m.Customer.Name)
[...]
至
@使用(Html.BeginForm(“UpdateCustomer”、“Account”))
{
@LabelFor(m=>m.Customer.Name)
@TextBoxFor(m=>m.Customer.Name,新的{@class=“form control”})
@Html.ValidationMessageFor(m=>m.Customer.Name)
[...]
@Html.HiddenFor(m=>m.Customer.Id)
}
Javascript文件
希望能有所帮助。使用按钮类型按钮而不是提交,表单提交默认采用GET方法我不认为是这种情况,因为我在同一应用程序中的其他ajax请求中尝试了该方法,它们似乎工作得很好。这只是一个猜测,如果是我,我会再次检查我的jQuery版本。。。有可能您已经尝试过方法:get(无论如何这是默认的)您是一个救生员,非常感谢。此外,this.serialize实际上做什么?为什么会有这样的行为