我有以下形式
<form class="regForm" id="frmRegistration" method="post">
<h3>Register Customer Patient</h3>
@Html.ValidationSummary(true)
@Html.LabelFor(m => m.LastName)
@Html.TextBoxFor(m => m.LastName, new { @class = "form-control cfield", required = "required", autofocus = "autofocus" })
@Html.LabelFor(m => m.FirstName)
@Html.TextBoxFor(m => m.FirstName, new { @class = "form-control cfield", required = "required" })
@Html.LabelFor(m => m.MiddleName)
@Html.TextBoxFor(m => m.MiddleName, new { @class = "form-control cfield", required = "required" })
@Html.LabelFor(m => m.BirthDate)
@Html.TextBoxFor(m => m.BirthDate, new { @class = "form-control cfield", required = "required" })
@Html.LabelFor(m => m.Address)
@Html.TextBoxFor(m => m.Address, new { @class = "form-control cfield", required = "required" })
<button type="submit" id="btnSave" class="btnreg btn btn-primary form-control">REGISTER</button>
<button type="button" onclick="clearTexts();" class="btnClear btn btn-danger form-control">CLEAR</button>
下面是我要触发/调用的控制器操作方法
[HttpPost]
public ActionResult AddCustomerPatient(Customer _Customer)
{
using (var db = new DCDBEntities())
{
db.Customers.Add(_Customer);
db.SaveChanges();
}
return Json(new {registeredCustomer="ok"});
}
下面是我的jquery ajax,它不起作用
$("#btnSave").click(function () {
e.preventDefault();
var PotentialCustomer = {
"LastName": 'A',
"FirstName": 'A',
"MiddleName": 'A',
"BirthDate": 'A',
"Address": 'A'
};
$.ajax({
type: 'POST',
url: '/Registration/AddCustomerPatient',
data: 'JSON.stringify(PotentialCustomer),',
contentType: "application/json; charset=utf-8",
dataType: 'json',
success: function (response) {
alert("Successfully Registered Customer/Patient!");
}
});
});
问题 1.(控制器操作方法未命中(我放置了一个断点(
问题 2.(如何将模型传递给控制器操作方法,并通过 linq 将其保存到实体。
我一直在寻找并尝试了很多,但仍然无法完成。
下面是路由配置
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
我试图在控制器的GET或第一个方法中放置一个断点,每当我单击"注册"按钮时,它都会被击中而不是[HttpPost],这是为什么?
public ActionResult RegisterCustomerPatient()
{
return View();
}
[HttpPost]
public ActionResult AddCustomerPatient(Customer _Customer)
{
using (var db = new DCDBEntities())
{
db.Customers.Add(_Customer);
db.SaveChanges();
}
return Json(new {registeredCustomer="ok"});
}
我是否需要为 HTTPPOST 操作方法创建视图?
var formData = $('#frmRegistration').serialize();
$.ajax({
type: 'POST',
url: '@Url.Action("AddCustomerPatient", "Registration")',
data: formData,
success: function (response) {
alert("Successfully Registered Customer/Patient!");
}
});
最好序列化表单数据并将其发送到控制器操作方法
data: 'JSON.stringify(PotentialCustomer(,'
请删除单引号。会没事的data: JSON.stringify(PotentialCustomer(,
问题是行
data: 'JSON.stringify(PotentialCustomer),',
和
click(function () {
// e is undefined here. Add e as parameter in function.
e.preventDefault();
JSON.stringify 应该用作函数而不是字符串。在上面,它被用作字符串。将其更改为以下(假设模型中的所有字段都是字符串(
$("#btnSave").click(function (e) {
e.preventDefault();
var PotentialCustomer = {
"LastName": 'A',
"FirstName": 'A',
"MiddleName": 'A',
"BirthDate": 'A',
"Address": 'A'
};
$.ajax({
type: 'POST',
url: '/Registration/AddCustomerPatient',
data: JSON.stringify(PotentialCustomer),
contentType: "application/json; charset=utf-8",
dataType: 'json',
success: function (response) {
alert("Successfully Registered Customer/Patient!");
}
});
,里面的数据
data: 'JSON.stringify(PotentialCustomer(',
接下来我不确定,但请尝试
data:{'_customer':'PotentialCustomer'};而不是 data.strinify
问题 1.(控制器操作方法未被击中
我认为这是由 ajax 帖子的错误 URL 引起的。您可以尝试在浏览器上打开开发人员工具的网络选项卡以确认这一点。如果你的ajax帖子返回HTTP状态404,你应该更新你的ajax帖子的URL。
获取正确 URL 的一种方法是使用 @Url.Action 添加提交按钮的 URL 属性。
<button type='button' id='btnSave' data-url='@Url.Action("AddCustomerPatient", "Registration")' class='btnreg btn btn-primary form-control'>REGISTER</button>
然后你可以在点击函数中得到这个值,就像这样
$("#btnSave").data('url')
问题 2.(如何将模型传递给控制器操作方法,并通过 linq 将其保存到实体。
获得正确的URL后,您应该更新点击功能
$("#btnSave").click(function () {
var formData = $('#frmRegistration').serialize();
$.ajax({
type: 'POST',
url: $("#btnSave").data('url'),
data: formData,
success: function (response) {
alert("Successfully Registered Customer/Patient!");
}
});
});
替代方法
我猜你想做一个ajax帖子而不是提交表单,所以你可以尝试另一种简单的方法,如下所示。
剃须刀代码
@using (Html.BeginForm("AddCustomerPatient", "Registration", FormMethod.Post, new { id = "frmRegistration"))
{
...
<button type="submit" id="btnSave" class="btnreg btn btn-primary form-control">REGISTER</button>
<button type="button" onclick="clearTexts();" class="btnClear btn btn-danger form-control">CLEAR</button>
}
脚本
$(function () {
$("#frmRegistration").on('submit', function (e) {
e.preventDefault(); // prevent the form's normal submission
var $form = $(this);
var dataToPost = $form.serialize();
$.post($form.attr('action'), dataToPost)
.done(function(response, status, jqxhr){
// this is the "success" callback
})
.fail(function(jqxhr, status, error){
// this is the ""error"" callback
});
})
})
你的ajax请求应该是这样的
$("#btnSave").click(function (e) { //added e
e.preventDefault();
var _Customer= { //changed the name to name of parameter of action
"LastName": $("#LastName").val(),
"FirstName": $("#FirstName").val(),
"MiddleName": $("#MiddleName").val(),
"BirthDate": $("#BirthDate").val(),
"Address": $("#Address").val()
};
$.ajax({
type: 'POST',
url: '/Registration/AddCustomerPatient',
data: JSON.stringify(_Customer), //removed '' and corrected the format
contentType: "application/json; charset=utf-8",
dataType: 'json',
success: function (response) {
alert("Successfully Registered Customer/Patient!");
}
});
});
JSON.stringify
是一个函数,因此不应将其放置在''
内JSON.stringify(_Customer)
并且对象名称应与Customer _Customer
的Action参数名称匹配,并且您在没有在参数中添加e
的情况下使用了e.preventDefault();