简体   繁体   English

将表单发送到ajax中的控制器

[英]Send form to controller in ajax

This is my form 这是我的表格

<form id="postProblemForm" action="/Problems/Post"  method="post" enctype="multipart/form-data">
            <input type="text" id="problemSubject" name="problemSubject" class="inp-form"/>
            <input type="file" id="uploadFile" name="uploadFile"/>
            <textarea rows="" cols="" class="form-textarea" id="problemDescription" name="problemDescription"></textarea>
            <input type="submit" value="Post" id="btnPostProblem"  style="width:70px;"/>

    </form>

following is JS 以下是JS

$("#postProblemForm").submit(function (event) {
                event.preventDefault();
                var $this = $(this);
                var url = $this.attr('action');
                var dataToSend = $this.serialize();
                var callBack = function (isPosted) {
                                    if (isPosted) { alert("posted successfully"); } }
                $.get(url,dataToSend,callBack);

            });

Following is Controller code 以下是控制器代码

[HttpPost]
        public bool Post(FormCollection form) 
        {
            string subject = form["problemSubject"];
            string description = form["problemDescription"];
            var image = WebImage.GetImageFromRequest();

            return true;

        }

But controller method is not being called. 但是没有调用控制器方法。 Plese help. 请帮助。

You cannot upload files using AJAX. 您无法使用AJAX上传文件。 I see that your form contains a file input but this won't work with AJAX. 我看到你的表单包含一个文件输入,但这不适用于AJAX。 Also you are using a $.get whereas you probably wanted to $.post the contents. 你也使用$.get而你可能想要$.post内容。 Another issue with your action is that it should return an ActionResult and not boolean types. 你的行动的另一个问题是它应该返回一个ActionResult而不是布尔类型。 For example you could return a JsonResult for tat matter. 例如,你可以返回一个JsonResult。

If you want to be able to upload files with your form you could use a client side upload plugin such as Uploadify , Fine Uploader or the jQuery.form plugin . 如果您希望能够使用表单上传文件,可以使用客户端上传插件,例如UploadifyFine UploaderjQuery.form plugin

Here's for example how your code might look like with the jQuery.form plugin: 以下是jQuery.form插件的代码示例:

$('#postProblemForm').ajaxForm(function(isPosted) {
    if (isPosted) { 
        alert('posted successfully');
    }
});

You're doing a GET on a controller method that accepts a POST request. 您正在对接受POST请求的控制器方法执行GET操作。 You need to change it to: 您需要将其更改为:

$.post(url,dataToSend,callBack);

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

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