我有以下表格
<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将其保存到实体。
我一直在寻找并尝试了很多但仍然无法完成它。
下面是routconfig
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
每当我点击&#34; REGISTER&#34;我试图在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操作方法创建一个视图?
答案 0 :(得分:1)
var formData = $('#frmRegistration').serialize();
$.ajax({
type: 'POST',
url: '@Url.Action("AddCustomerPatient", "Registration")',
data: formData,
success: function (response) {
alert("Successfully Registered Customer/Patient!");
}
});
更好地序列化表单数据并将其发送到控制器操作方法
答案 1 :(得分:1)
问题在于行
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!");
}
});
答案 2 :(得分:1)
数据:&#39; JSON.stringify(PotentialCustomer),&#39;
请删除单引号。 没事的 data:JSON.stringify(PotentialCustomer),
答案 3 :(得分:1)
有一个内部数据
数据:'JSON.stringify(PotentialCustomer),',
接下来我不确定但是试试
数据:{ '_顾客': 'PotentialCustomer'}; 而不是data.strinify
答案 4 :(得分:1)
问题1.)控制器操作方法没有被点击
我认为这是由ajax帖子的错误网址引起的。您可以尝试在浏览器上打开Developer Tool的Network选项卡进行确认。你回复HTTP状态404 ajax,你应该更新你的ajax帖子的URL 获取正确网址的一种方法是使用@ Url.Action添加提交按钮的网址属性。
<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将其保存到实体。
获取正确的网址后,您应该更新点击功能
$("#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
});
})
})
答案 5 :(得分:0)
你的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)
对象名称应与Action Customer _Customer
的参数名称匹配,并且您也使用e.preventDefault();
未在参数
e