【问题标题】:How to call a method using AJAX inside of a form?如何在表单内使用 AJAX 调用方法?
【发布时间】:2013-02-05 05:48:43
【问题描述】:

在这个剃刀视图中,我有两个按钮,分别称为上一个和下一个。当用户按下这些按钮时,我需要调用一个存储用户类型的方法:

@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(我猜)以来,是否有可能调用一个动作方法?

【问题讨论】:

  • 将传递给操作方法的值是什么?整个模型?
  • @DaveA 是的,整个模型

标签: c# ajax jquery asp.net-ajax


【解决方案1】:

您也可以使用 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;
    }
}

【讨论】:

  • 是否可以将整个模型传递给方法?我的意思是,而不是FormCollection
  • 是的,您可以使用 jQuery 序列化并发送表单。如果输入名称与模型变量名称相同,它将被选为模型。
【解决方案2】:

你可以

$.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)
    {
...
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-30
    • 1970-01-01
    • 2015-05-19
    相关资源
    最近更新 更多