通过AJAX提交表单,并返回一个局部视图 - MVC2视图、表单、局部、AJAX

2023-09-10 18:21:54 作者:卖萌失败

好像有很多方法可以解决这个问题。

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>

然后我劫持提交使用jQuery,做一个ajax后,并用另一个局部视图替换形式:

then I hijack the submit with JQuery and do an ajax post and replace the form with another partial view:

$(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");
    }

我的问题

有什么其他的方法来完成同样的事情,什么是利弊VS我在做什么?

My Question

What are other ways to accomplish the same thing and what are the pros and cons vs what I am doing?

时Ajax.Form有用吗?

Is Ajax.Form useful?

推荐答案

有什么不好,你正在做的方式吗?我已经做了这样的说法,它的作品对我来说。这取决于你如何可重复使用的需要做出的程序;你可以使用一个DIV与CSS类,然后创建一个jQuery插件或控件,如果你需要的可重用性。

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.

HTH。