ajax - Ajax call with .net MVC
问题描述
I am trying to use Ajax to Submit a form. But when I do submit the page is reloaded and the url changes. I think that the url changes because of the @Html.AntiForgeryToken();
See my code bellow :
This is how my form looks like :
@model PersonModel
....
<form action="SubmitLead" class="new-lead">
@Html.AntiForgeryToken();
<div class="col-md-12">
<p>
<input type="hidden" value="@Model.TrackingCode" id="hdnTrackingCode" />
My name is @Html.TextBoxFor(model => model.FirstName,
new { @placeholder =
Html.DisplayNameFor(model => model.FirstName) })
@Html.TextBoxFor(model => model.Surname, new { @placeholder = Html.DisplayNameFor(model => model.Surname) })
</p>
</div>
<div class="clearfix"></div>
<div class="col-md-12 text-center">
<button type="submit" id="btnSubmit" class="orange-button">Get Quotes Now</button>
</div>
</form>
@if (Model.Results != null &&
Model.Results.IsSuccessful)
{
<div class="col-md-12 text-center">
<img src="~/Content/Images/Products/new-success.png" height="24px" />
<p id="result"></p>
</div>
}
Please see my script here :
@section Scripts{
<script type="text/javascript">
$(document).ready(function () {
$('.new-lead').submit(function (event) {
$.ajax({
url: '@Url.Action("Lead/SubmitLead")',
type: 'POST',
data: $(this).serialize(),
dataType: 'json',
success: function (result) {
var resultMessage = "success";
$('result').html(resultMessage);
}
})
})
})
</script>
解决方案
Do this way
<form onsubmit="return submit(thi)" class="new-lead">
....
</form>
<script>
function submit(e){
$.ajax({
url: '@Url.Action("Lead/SubmitLead")',
type: 'POST',
data: $(e).serialize(),
dataType: 'json',
success: function (result) {
var resultMessage = "success";
$('result').html(resultMessage);
}
})
return false;
}
</script>
推荐阅读
- python - 在 Python 中将数据保存到 json 文件
- bash - 如何为 Bash 脚本中的所有操作提供一次密码?
- xamarin - libvlc RTSP ip camera "libvlc demux: SETUP of'video/H264' failed 403 Forbidden" Qihan IP Camera Model:QH-NW357
- windows - 在 golang 中添加和生成自定义系统调用
- r - 我在一个列表中有 4000 个数据框。想在列表的每个数据帧上使用 group_by 应用汇总函数
- ruby-on-rails - 语法错误,意外的keyword_ensure,在我的应用程序中期待keyword_end
- android - 在 RunTime 上创建 edittext 时,Edittext 隐藏在键盘下
- javascript - NavLink 中的 ActiveClassName 需要重新加载页面才能显示
- c# - ASP.NET 核心在单例服务上调用异步初始化
- python - Win32com Outlook 组联系人