简体   繁体   English

通过AJAX提交表单并返回部分视图-MVC2

[英]Submit a Form via AJAX and Return a Partial View - MVC2

Seems like there are a lot of ways to solve this problem. 似乎有很多方法可以解决此问题。

Currently I make a partial view with a form like so: 目前,我使用这样的形式进行部分查看:

<div id="container">
    <form id="some-form">
        <input id="some-text" type="text">
        <input id="some-submit" type="submit">
    </form>
</div>

then I hijack the submit with JQuery and do an ajax post and replace the form with another partial view: 然后我用JQuery劫持了Submit并进行了ajax发布,并用另一个局部视图替换了表单:

$(function()
{
    $('#some-form').submit(function(){
          $.ajax({
               type: "POST",
               url: "/Controller/Action",
               data: {someVal: $('#some-text').val()},
               dataType: "html",
               success: function (result) {
                   $('#container').html(result);
               },
               error: function (request, status, error) {
                   alert('Oh no!');
               }
         });
    });
});

The controller would be like: 控制器将像:

    [HttpPost]
    public ActionResult SomeAction(string someVal)
    {
        //Do something with text
        return PartialView("SubmitSuccess");
    }

My Question 我的问题

What are other ways to accomplish the same thing and what are the pros and cons vs what I am doing? 还有什么其他方法可以完成同一件事?与我在做什么又有什么利弊?

Is Ajax.Form useful? Ajax.Form有用吗?

Personally I use the jquery form plugin . 我个人使用jquery表单插件 It will make your code shorter. 它将使您的代码更短。 Also assign the action parameter to your form to avoid hardcoding it in your scripts. 还要将动作参数分配给表单,以避免在脚本中对其进行硬编码。

<div id="container">
    <% using (Html.BeginForm("action", "controller", FormMethod.Post, 
        new { id = "some-form" })) { %>
        <input id="some-text" type="text">
        <input id="some-submit" type="submit">
    <% } %>
</div>

And then attach the plugin to this form to AJAXify it: 然后将插件附加到此表单以对其进行AJAXify:

$(function() {
    $('#some-form').ajaxForm({
        success: function(result) { 
            $('#container').html(result);
        },
        error: function(request, status, error) {
            alert('Oh no!');
        }
    });
});

The plugin will automatically send an AJAX request to the action, using the verb specified in the method parameter and serializing the values of all input fields in the request. 插件将使用method参数中指定的动词并序列化请求中所有输入字段的值,将AJAX请求自动发送到操作。

What's wrong with the way that you are doing? 你做事的方式怎么了? I've done it that way, and it works out for me. 我已经这样做了,对我来说很有效。 It depends how reusable you need to make the process; 这取决于您需要使流程具有多大的可重用性。 you could use a DIV with a css class, and then create a JQuery plugin or widget if you need reusability. 您可以将DIV与CSS类一起使用,如果需要可重用性,则可以创建一个JQuery插件或小部件。

HTH. HTH。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM