简体   繁体   English

用jquery ajax和MVC3发布表单的正确方法是什么?

[英]What is the correct way of posting a form with jquery ajax and MVC3?

I've seen a couple of methods on how to do this. 我已经看到了两种方法。 My own method that I like, except from one part, is the following: 除了一部分之外,我喜欢的我自己的方法如下:

  1. Hijack submit-event of form 劫持表单的提交事件
  2. Collect the data and build a json object 收集数据并构建一个json对象

     var objToSend = { Property : $('#propertyField').val(), Property2 : ... }; 

    This is the part I don't like since it's tedious to collect 25 values like this 这是我不喜欢的部分,因为收集这样的25个值很繁琐

  3. Call $.ajax({}) and specify the url to point to an [HttpPost] enabled action somewhere 调用$.ajax({})并指定url指向某处启用[HttpPost]操作

  4. in the success: part of the ajax-query, collect the returned data (which I return as a string) and write it out where appropriate. 成功:ajax查询的一部分,收集返回的数据(我以字符串形式返回)并在适当的地方将其写出。 I handle errors here as well, checking to see if the first word is "Error:" and then taking appropriate action. 我也在这里处理错误,检查第一个单词是否为“ Error:”,然后采取适当的措施。

I like this method apart from the collection stage. 除了收集阶段,我喜欢这种方法。 I am sure there is a better way of doing this but I'v thrown myself headlong into jquery coming from an ASP.NET WebForms-background so the whole "embrace the web" part is totally foreign to me. 我敢肯定有更好的方法可以做到这一点,但是我已经把自己扔进了来自ASP.NET WebForms背景的jquery中,所以整个“拥抱Web”部分对我来说完全是陌生的。

You could use the serialize() method to avoid passing all the fields one by one. 您可以使用serialize()方法避免一一传递所有字段。 It will send the entire form data to the server using application/x-www-form-urlencoded content type as if it was a standard form submission: 它将使用application/x-www-form-urlencoded内容类型将整个表单数据发送到服务器,就好像它是标准表单提交一样:

$('#myform').submit(function() {
    $.ajax({
        url: this.action,
        type: this.method,
        data: $(this).serialize(),
        success: function(result) {
            // TODO: handle the success case
        }     
    });
    return false;
});

Another possibility is the jQuery form plugin : 另一种可能性是jQuery表单插件

$('#myform').ajaxForm(function(result) { 
    // TODO: handle the success case
});

Some people find it also useful to use the Ajax.BeginForm helpers to render the form: 有人发现使用Ajax.BeginForm帮助器呈现表单也很有用:

@using (Ajax.BeginForm(new AjaxOptions { OnSuccess = "success" }))
{
    ... some input fields
}

In ASP.NET MVC 3 you need to include the jquery.unobtrusive-ajax.js script which unobtrusively AJAXifies the HTML 5 data-* attributes emitted by the Ajax helper. 在ASP.NET MVC 3中,您需要包括jquery.unobtrusive-ajax.js脚本,该脚本可以毫不夸张地对Ajax帮助程序发出的HTML 5 data-*属性进行AJAX。

Allow jQuery to build your json for you. 允许jQuery为您构建json。 You can serialize a form which will create a data set for you to submit. 您可以序列化一个表格,该表格将创建一个数据集供您提交。

$.post("myUrl", 
       $("form").serialize(), 
       function(callback) { ... } 
     );

That's how I'd do it! 我就是那样做的!

You also have the option of using the MVC helpers to create the post code handling code for you if you're dealing with a form eg 如果您正在处理表单,例如,您还可以选择使用MVC帮助器为您创建邮政编码处理代码。

<% using (html.BeginForm()) {%>

    // html for the form


    <input type='submit' value='post' />

<% } %>

The transition from WebForms to MVC can be a tricky one for people has you really are dealing with the raw aspects of web programming ie http, html and javascript... BTW I believe this to be a good thing as I'm not a fan of the pseudo single process event model of WebForms. 从WebForms到MVC的过渡对于您来说确实是一件棘手的事情,如果您确实正在处理Web编程的原始方面,即http,html和javascript ...顺便说一句,我相信这是一件好事,因为我不是粉丝WebForms的伪单进程事件模型。

Long live MVC! MVC万岁! :) :)

I tend to use the "jQuery form plugin". 我倾向于使用“ jQuery表单插件”。 It allows you to cleanly abstract a standard form into an AJAX form with very little effort: 它使您可以轻松地将标准表单完全抽象为AJAX表单:

http://jquery.malsup.com/form/ http://jquery.malsup.com/form/

It also allows you to easily trap various events, failure conditions, validations etc and can convert your form to a JSON request or XML if you desire. 它还使您可以轻松捕获各种事件,失败情况,验证等,并且可以根据需要将表单转换为JSON请求或XML。 Handles file uploads too. 也处理文件上传。

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

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