Jquery 在ajax mvc中用表单替换json结果
我的看法与此相同Jquery 在ajax mvc中用表单替换json结果,jquery,json,ajax,model-view-controller,Jquery,Json,Ajax,Model View Controller,我的看法与此相同 <div class="col-sm-3 "> @{Html.RenderAction("Subscribe", "Home");} </div> 在partialview中是 @model Jar.Models.Subscribe <div Id="subForm" class="single-widget"> @using (Html.BeginForm()) {
<div class="col-sm-3 ">
@{Html.RenderAction("Subscribe", "Home");}
</div>
在partialview中是
@model Jar.Models.Subscribe
<div Id="subForm" class="single-widget">
@using (Html.BeginForm()) {
@Html.TextBoxFor(x => x.Email, new { htmlAttributes = new {
@class = "form-control", @placeholder = "email" } })
<button type = "submit" id = "btn_Subscribe" class="btn btn-default"><i class="fa fa-arrow-circle-o-left"></i></button>
}
}))
好的,当点击订阅按钮时,我想发送电子邮件到数据库,返回json并用所有订阅表单(文本框和按钮)替换json,
现在,当我点击订阅,电子邮件注册,但返回到新的页面与简单的文字“订阅是投诉,请检查您的电子邮件”
如何更改此代码以将订阅表单替换为json文本?首先,我建议将您的事件挂接到
form
元素的submit
方法
其次,您应该将响应类型更改为对象,以便更有效地将其编码为JSON,并且响应更一致:
[HttpPost]
public ActionResult Subscribe(Subscribe subscribe)
{
if (ModelState.IsValid)
{
// your code...
return Json(new { Message = "subscribe is complate, please check your email" }, JsonRequestBehavior.AllowGet);
}
return Json(new { Message = "error" }, JsonRequestBehavior.AllowGet);
}
最后,为了实现您的目标,您可以使用text()
方法查看包含表单的div
的内容,它将替换该内容。试试这个:
$("#subForm form").on('submit', function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: '@Url.Action("Subscribe")',
dataType: 'json',
data: {
Email: $("#Email").val()
},
success: function(data) {
$('#subForm').text(data.Message); // note the use of text() here
}
});
});
我使用它,但当我点击按钮页面刷新和显示源代码对不起!我的错误-我忘了向事件添加
preventDefault()
调用
[HttpPost]
public ActionResult Subscribe(Subscribe subscribe)
{
if (ModelState.IsValid)
{
// your code...
return Json(new { Message = "subscribe is complate, please check your email" }, JsonRequestBehavior.AllowGet);
}
return Json(new { Message = "error" }, JsonRequestBehavior.AllowGet);
}
$("#subForm form").on('submit', function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: '@Url.Action("Subscribe")',
dataType: 'json',
data: {
Email: $("#Email").val()
},
success: function(data) {
$('#subForm').text(data.Message); // note the use of text() here
}
});
});