javascript - 如何在 MVC 5 中通过单个 Ajax POST 请求发送 ViewModel 和文件?

标签 javascript c# ajax asp.net-mvc asp.net-mvc-5

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

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

这是 Controller Action :

[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 代码:

$('#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) { }
    });
});

问题是,当请求到达 Controller 操作时,我有文件和填充的“userId”,但“model”参数始终为空。我在填充 FormData 对象时做错了什么吗?

最佳答案

这是我用 MVC5 和 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>

Controller

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 的 answer

关于javascript - 如何在 MVC 5 中通过单个 Ajax POST 请求发送 ViewModel 和文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32802468/

相关文章:

javascript - 将一个简单的数组转换为复杂的对象,并将项目作为子数组

javascript - 通过Javascript触发<a href =""/>的点击(跨浏览器解决方案)

c# - 在 ASP.NET 中将 GridView 导出到 Excel 时如何设置波斯语字符编码?

javascript - 如何通过 HTTP POST 将 Blob 发送到不同的域?

javascript - Ajax 函数在第二次运行之前没有完成

javascript - select 中的 ng-options 返回对象而不是字符串

javascript - 在繁忙的 JavaScript 代码期间页面未更新

c# - 通过 SharePoint Web 服务在文件夹中添加权限

c# - 从 HttpWebRequest 对象获取正文?

javascript - ajax帖子为空(数据库中的空字符串)