jQuery 使用 Ajax 将表单数据发布到控制器的操作

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10317141/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 09:07:54  来源:igfitidea点击:

Post form data to Controller's action with Ajax

ajaxasp.net-mvc-3jqueryasp.net-ajax

提问by bzamfir

I have a page in MVC3, with a link (Ajax.ActionLink). When user clicks it, it calls controller's action, and the result is inserted into a div, with replace.

我在 MVC3 中有一个页面,带有一个链接 (Ajax.ActionLink)。当用户点击它时,它会调用控制器的动作,并将结果插入到一个 div 中,并带有替换。

Code is shown below:

代码如下所示:

@Ajax.ImageActionLink("/Images/btn_share.png", "Share pool", "SharePool", new { poolKey = Model.Id, poolName = Model.Name },
    new AjaxOptions { 
        UpdateTargetId="popup", 
        HttpMethod="GET", 
        InsertionMode = InsertionMode.Replace,
        LoadingElementId="loading_dialog",
        OnSuccess = "ShowPopup('#popup_share', true, true)"
    } 

ImageLinkAction is custom extension method to use image as link, and ShowPopup is a javascript function that shows the updated div (to make it look as a popup)

ImageLinkAction 是使用图像作为链接的自定义扩展方法,ShowPopup 是一个 javascript 函数,用于显示更新的 div(使其看起来像一个弹出窗口)

Now the markup code inserted into the div which creates the popup contains a form as below

现在插入到创建弹出窗口的 div 中的标记代码包含一个如下所示的表单

<div>
@using (Html.BeginForm()) {

    @Html.HiddenFor(model => model.ID)

    <div class="editor-label">
        @Html.LabelFor(model => model.EmailAddress)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.EmailAddress)
        @Html.ValidationMessageFor(model => model.EmailAddress)
    </div>

    // ... other fields

    @Html.ValidationSummary(true)
    <p>
        <button type ="submit">Share</button>       
    </p>
}
</div>

The issue is with the form's submit: the Submit button calls the proper action but with a postback, which cause my page to refresh. What I need is to post data with ajax, receive the response, which is another partial view that gets inserted into the

问题出在表单的提交上:提交按钮调用了正确的操作,但带有回发,这会导致我的页面刷新。我需要的是用ajax发布数据,接收响应,这是另一个插入到

I was trying to replace the Submit button with Ajax.ActionLink as below

我试图用 Ajax.ActionLink 替换提交按钮,如下所示

    @Ajax.ActionLink("Share", "Share",
        new Models.MyModel 
            {
                ID = Model.ID,
                EmailAddress = Model.EmailAddress
            },
        new AjaxOptions
            {
                UpdateTargetId="popup", 
                HttpMethod="POST", 
                InsertionMode = InsertionMode.Replace,
                LoadingElementId="loading_dialog",
                OnSuccess = "ShowPopup('#popup_share', true, true)"
            }

The controller's code looks like this:

控制器的代码如下所示:

[HttpPost]
public ActionResult SharePool(MyModel model)
{
    // ...
    return PartialView("_MyPartialView", model)
}

The problem is, in the moment the Ajax ActionLink is rendered (when form is loaded) there is no value in Model.EmailAddress, so my POST action in controller receives only ID parameter.

问题是,在呈现 Ajax ActionLink 的那一刻(加载表单时),Model.EmailAddress 中没有值,因此控制器中的 POST 操作仅接收 ID 参数。

How can I handle this? Ideally, I think I should add

我该如何处理?理想情况下,我认为我应该添加

OnBegin = "PreparePostData()"

But since I know javascript only basically, I have no idea how can I implement this. I think this PreparePostData() should collect form fields and prepare the object routeValues parameter, to be set before the ajax call is invoked.

但由于我只基本了解 javascript,我不知道如何实现这一点。我认为这个 PreparePostData() 应该收集表单字段并准备对象 routeValues 参数,在调用 ajax 调用之前设置。

Anyone can give me some indications on how to implement this?

任何人都可以给我一些关于如何实现这一点的指示?

Or is any other, better approach on this problem?

或者有没有其他更好的方法来解决这个问题?

Thank you

谢谢

回答by DMulligan

I'd recommend just writing your own AJAX calls with jQuery. It's more flexible than MVC's helpers anyway

我建议只使用 jQuery 编写您自己的 AJAX 调用。无论如何它比MVC的助手更灵活

@Html.ActionLink("Share", "Share", new { }, new { id = "share" })

And then a function

然后是一个函数

$("#share").click(function (e) {
   e.preventDefault();
   //Show loading display here
   var form= $("#shareForm");
   $.ajax({
       url : '@Url.Action("Share")',
       data: form.serialize(),
       type: 'POST',
       success: function(data){
          //Show popup
          $("#popup").html(data);
       }
   });
});

回答by a.boussema

When you do have multiple Forms on same Page (imagine the case y're showing/hiding on demand), you need to add Form before the #Id as Follows :

当您在同一页面上有多个表单时(想象一下您按需显示/隐藏的情况),您需要在 #Id 之前添加表单如下:

$("#share").click(function (e) {
   e.preventDefault();
   //Show loading display here

// Need to add Form before #id 
   var form= $("Form#share");

   $.ajax({
       url : '@Url.Action("Share")',
       data: form.serialize(),
       type: 'POST',
       success: function(data){
          //Show popup
          $("#popup").html(data);
       }
   });
);