如何在表单内部使用AJAX调用方法
本文关键字:AJAX 调用 方法 内部 表单 | 更新日期: 2023-09-27 17:57:32
在这个剃刀视图中,我有两个按钮,分别称为previous和next。当用户按下这些按钮时,我需要调用一个存储用户类型的方法:
@using (Html.BeginForm("Index", "Quiz", FormMethod.Post))
{
<div style="border-bottom: 2px solid #c8c8c8; overflow: auto; width: 100%">
<h2 class="float-left" style="padding-bottom:5px;">@Model.Quiz.Name</h2>
<div class="float-right">
<input name="button" type="submit" value="done" />
</div>
</div>
@for( ...) {
...
}
<div class="fixednavcontainer">
<div id="questionnav" class="content-wrapper">
<div id="questionnavstatus" class="float-left">
<p>
Question <span id="currentPage">@ViewBag.CurrentPage</span> of <span id="totalPages">@ViewBag.TotalPages</span>
</p>
</div>
<div id="navbuttons" class="float-right">
<img id="previous" src="~/Images/previous.png" />
<img id="next" src="~/Images/next.png" />
</div>
<div class="clear-fix" />
</div>
</div>
像这样的东西应该称之为按钮
private void Save(@model model)
{
...
}
我希望ajax不刷新页面的任何内容或加载另一个页面,只保存并保持相同的页面。从jquery(我想)开始,调用一个操作方法有可能做到这一点吗?
您也可以使用jQuery并进行如下调用:
var myModel = @Html.Raw(Json.Encode(MyModel)); //MVC3
$.ajax({
type: "POST",
url: "/MyController/SomeAction/",
data: myModel ,
cache: false,
dataType: "json",
success: function (response) {
// Do whatever you have to do...
}
});
在你的控制器里有这样的东西:
public class MyController
{
[HttpPost]
public ActionResult SomeAction(MyModel myModel)
{
// Do whatever and return whatever
return true;
}
}
您可以只使用
$.ajax({
type: "POST",
url: "@Url.Action('yourAddress')",
data: parametr,
cache: false,
dataType: "json",
success: function (response) {
// Do whatever you have to do...
}
});
和控制器
public class XController
{
[HttpPost]
public ActionResult yourAddress(YourModel)
{
...
}
}