在MVC 5中,如何在单个Ajax POST请求中发送ViewModel和文件? [英] How to send ViewModel and a file in single Ajax POST request, in MVC 5?

查看:74
本文介绍了在MVC 5中,如何在单个Ajax POST请求中发送ViewModel和文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个ASP.NET MVC 5应用程序.我正在尝试发送带有Model数据的POST请求,并且还包括用户选择的文件. 这是我的ViewModel(为简化起见,进行了简化):

I have an ASP.NET MVC 5 application. And I'm trying to send a POST request with the Model data, and also include user selected files. Here is my ViewModel (simplified for clarity):

public class Model
{
    public string Text { get; set; }
    public long Id { get; set; }
}

这是控制器操作:

[HttpPost]
public ActionResult UploadFile(long userId, Model model)
{
    foreach (string file in Request.Files)
    {
        // process files
    }

    return View("Index");
}

HTML输入元素:

<div>
    <input type="file" name="UploadFile" id="txtUploadFile" />
</div>

和JavaScript代码:

And the JavaScript code:

$('#txtUploadFile').on('change', function (e) {
    var data = new FormData();
    for (var x = 0; x < files.length; x++) {
        data.append("file" + x, files[x]);
    }
    data.append("userId", 1);
    data.append("model", JSON.stringify({ Text: 'test text', Id: 3 }));

    $.ajax({
        type: "POST",
        url: '/Home/UploadFile',
        contentType: false,
        processData: false,
        data: data,
        success: function (result) { },
        error: function (xhr, status, p3, p4) { }
    });
});

问题是当请求到达控制器操作时,我有文件和'userId'填充,但是'model'参数始终为null.填充FormData对象时我做错什么了吗?

The problem is that when the Request reaches controller action, I have files and 'userId' populated, but 'model' parameter is always null. Am I doing something wrong when populating FormData object?

推荐答案

这是我与MVC5和IE11/chrome一起使用的测试

Here is what I test using with MVC5 and IE11 / chrome

查看

<script>
    $(function () {
        $("#form1").submit(function () {
            /*You can also inject values to suitable named hidden fields*/
            /*You can also inject the whole hidden filed to form dynamically*/
            $('#name2').val(Date); 
            var formData = new FormData($(this)[0]);
            $.ajax({
                url: $(this).attr('action'),
                type: $(this).attr('method'),
                data: formData,
                async: false,
                success: function (data) {
                    alert(data)
                },
                error: function(){
                    alert('error');
                },
                cache: false,
                contentType: false,
                processData: false
            });
            return false;
        });
    });
</script>

<form id="form1" action="/Home/Index" method="post" enctype="multipart/form-data">
    <input type="text" id="name1" name="name1" value="value1" />
    <input type="hidden" id ="name2" name="name2" value="" />
    <input name="file1" type="file" />
    <input type="submit" value="Sublit" />
</form>

控制器

public class HomeController : Controller
{
    [HttpGet]
    public ActionResult Index()
    {
        return View();
    }

    [HttpPost]
    public ActionResult Index(HttpPostedFileBase file1, string name1, string name2)
    {
        var result = new List<string>();
        if (file1 != null)
            result.Add(string.Format("{0}: {1} bytes", file1.FileName, file1.ContentLength));
        else
            result.Add("No file");
        result.Add(string.Format("name1: {0}", name1));
        result.Add(string.Format("name2: {0}", name2));
        return Content(string.Join(" - ", result.ToArray()));
    }
}

感谢Silver89的答案

Thanks to Silver89 for his answer

这篇关于在MVC 5中,如何在单个Ajax POST请求中发送ViewModel和文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆