使用Ajax将数据发送到控制器

时间:2016-12-12 14:33:47

标签: ajax asp.net-mvc

我有一个包含不同字段的表单供用户填写,并允许用户附加图像。下面是我将数据发送到控制器的代码,我可以在控制器中看到图像,但我不知道如何在控制器中访问其余的表单数据:

$(function () {
    var ajaxFormSubmit = function () {

        var $form = $(this);
        var data = new FormData();
        var files = $("#File").get(0).files;
        if (files.length > 0) { data.append("File", files[0]); }
        else {
            common.showNotification('warning', 'Please select file to upload.', 'top', 'right');
            return false;
        }


        var options = {
            url: $form.attr("action"),
            type: $form.attr("method"),
            data: data,
            processData: false,
            dataType: "html",
            contentType: false


        };
        $.ajax(options).done(function (data) {

            $('#ProdList').html(data);



        });
        return false;
    };
    $("form[data-ajax='true']").submit(ajaxFormSubmit);
});

我的控制器:

public ActionResult Create(PostViewProduct postProduct)
        {
//code......
}

PostViewProduct模型仅显示数据休息显示为null的图像字段: enter image description here

我是否必须使用formdata.append()添加每个字段,或者有更好的方法将所有数据发送到控制器,然后访问控制器中的数据。 感谢

3 个答案:

答案 0 :(得分:0)

尝试以下操作,如果所有输入都在表单内,这将使数据格式正确。

<a4j:form id="csv-form">
<a4j:htmlCommandLink title="Export" action="#{bean.export()}" value="Export CSV" id="csv-link"/>
<a4j:support event="onclick" reRender="results"></a4j:support>
</a4j:form>

答案 1 :(得分:0)

试试这个:

var data = new FormData($(this)[0]);

而不是var data = new FormData();

答案 2 :(得分:0)

您基本上需要将FormData中的文件与其他表单元素数据一起发送。

$(function () {          
    var ajaxFormSubmit = function () {

        var fdata = new FormData();

        $('input[name="Image"]').each(function (a, b) {
            var fileInput = $('input[name="Image"]')[a];
            if (fileInput.files.length > 0) {
                var file = fileInput.files[0];
                fdata.append("Image", file);
            }
        });

        // You can update the jquery selector to use a css class if you want
        $("input[type='text'").each(function (x, y) {
            fdata.append($(y).attr("name"), $(y).val());
        });

        var frmUrl = $(this).attr('action');
        $.ajax({
            type: 'post',
            url: frmUrl,
            data: fdata,
            processData: false,
            contentType: false,
            success: function (e) {
                console.log(e);
            }
        });
        return false;
    };
     $("form[data-ajax='true']").submit(ajaxFormSubmit);

});

假设您的视图模型有一个名为Image of HttpPostedFileBase的属性,用于接受已发布的文件,并且您的表单有一个输入

public class YourViewModel
{
   public HttpPostedFileBase Image { set;get;}
   //Your other existing properties
}

并且您的表单有一个文件输入标记,其名称为&#34;图像&#34;。

<input type="file" name="Image" />
相关问题