C# 在asp.net MVC中发布没有@HTML.Beginform的表单并使用Jquery(ajax)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18293538/
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-10 11:50:18  来源:igfitidea点击:

Posting form without @HTML.Beginform and using Jquery(ajax) in asp.net MVC

c#asp.net-mvcjquery

提问by Dimo

How can I fill out a form without using @HTML.Beginform and by using JQuery Ajax instead? Right now I tried:

如何在不使用 @HTML.Beginform 而是使用 JQuery Ajax 的情况下填写表单?现在我试过:

    var postData = { form1: username, form2: password };

    $.ajax({
        type: "POST",
        url: '/Controller/Method',
        data: postData,
        dataType: "json",
        traditional: true
    });

But after posting, the browser does not navigate to the correct view. Of course I have return View() correctly in controller. Using Fiddler I see that it's correctly posted and the response is correct too...

但是发布后,浏览器没有导航到正确的视图。当然,我在控制器中正确返回了 View()。使用 Fiddler 我看到它被正确发布并且响应也是正确的......

Do I haveto use @HTML.Beginform or can I do it with Ajax?

必须使用@HTML.Beginform 还是可以使用 Ajax 来完成?

采纳答案by Paul

Your can use either a raw HTML <form>tag or the @HTML.BeginFormhelper. Here is an example using just HTML

您可以使用原始 HTML<form>标记或@HTML.BeginForm帮助程序。这是一个仅使用的示例HTML

Complete solution:

完整的解决方案:

<form action"/Controller/Method" method="POST" id="signInForm">
    <input type="text" name="form1" />
    <input type="text" name="form2" />
    <input type="submit" value="Sign in" />
</form>

$( function() {
    $( 'signInForm' ).submit( function( evt ) {
        //prevent the browsers default function
        evt.preventDefault();
        //grab the form and wrap it with jQuery
        var $form = $( this );
        //if client side validation fails, don't do anything
        if( !$form.valid() ) return;
        //send your ajax request
        $.ajax( {
            type: $form.prop( 'method' ),
            url: $form.prop( 'action' ),
            data: $form.serialize(),
            dataType: "json",
            traditional: true,
            success: function( response ) {
                document.body.innerHTML = response;
            }
        });
    });
});

I recommend using @Url.Actionto set the URL of your form action. This way routing can generate your URL.

我建议使用@Url.Action来设置表单操作的 URL。通过这种方式路由可以生成您的 URL。

<form action"@Url.Action("Method", "Controller")" method="POST" id="signInForm">
    <input type="text" name="form1" />
    <input type="text" name="form2" />
    <input type="submit" value="Sign in" />
</form>

It is slightly more advanced, but I would try using something like Take Commandto manage your jQuery Ajax calls.

它稍微高级一些,但我会尝试使用诸如Take Command 之类的东西来管理您的 jQuery Ajax 调用。

Disclaimer, I am a contributor to the TakeCommand project.

免责声明,我是 TakeCommand 项目的贡献者。

回答by haim770

When you're using @Html.BeginForm, the HTML output is:

使用时@Html.BeginForm,HTML 输出为:

<form method="POST" action="/Controller/Method">

And when you submit that form, the browser handles it just like another page navigation (only using POSTmethod) hence the response is loaded into the parent frame.

当您提交该表单时,浏览器会像处理另一个页面导航(仅使用POST方法)一样处理它,因此将响应加载到父框架中。

But, when you're initiating an Ajaxrequest, it's up to you to handle the response from the server (typically using a callback function).

但是,当您发起Ajax请求时,由您来处理来自服务器的响应(通常使用回调函数)。

If you want to simulate the regular form submission behavior, it would be something like:

如果你想模拟常规的表单提交行为,它会是这样的:

$.ajax({
    type: "POST",
    url: '/Controller/Method',
    data: postData,
    dataType: "json",
    traditional: true,
    success: function(response)
    {
        document.body.innerHTML = response;
    }
});

This would not replace the entire page content with the response (only the BODYcontents) but in most cases it will be fine.

这不会用响应(仅BODY内容)替换整个页面内容,但在大多数情况下它会很好。

回答by Lars Anundsk?s

This will do a xhr post to the server and return the view as data (response) It will not navigate, if it returns html, you need to set a proper datatype in your request to tell that you expect html back from the server:

这将对服务器执行 xhr 发布并将视图作为数据(响应)返回它不会导航,如果它返回 html,则您需要在请求中设置正确的数据类型以告诉您希望从服务器返回 html:

Given your action returns html, you can put the returned html on your page in your success function.

鉴于您的操作返回 html,您可以将返回的 html 放在页面上的成功函数中。

postData = "{'ID':'test'}";
$.ajax({
    type: "POST",
    url: '/Home/Test',
    data: postData,
    dataType: 'html',
    contentType: 'application/json',
    traditional: true,
    success: function (data) {
        $("#yourdomelement").html(data);
    }
});

In your action;

在你的行动中;

public ActionResult Test([FromBody]PostData id)
{
    return Content("<p>hello</p>");
}