使用来自Ajax的MVC Razor上传文件 - 初学者逻辑问题

时间:2017-02-12 06:00:09

标签: javascript jquery ajax asp.net-mvc asp.net-ajax

我正在尝试使用C#-Razor使用AJAX上传文件。当我通过单击按钮提交时,控制器方法没有被执行。我该如何解决这个问题?

我的代码如下:

查看

<div class="form-group">
    @Html.TextBoxFor(model => model.IMG, new { @class = "control-label col-md-12", type = "file", placeholder = "Industry", name = "files[]", id="FileUpload" })
    @Html.LabelFor(model => model.IMG, new { @class = "col-md-12 " })
    @Html.ValidationMessageFor(model => model.IMG)
</div>
<div class="form-group">
    <div class="col-md-offset-2 col-md-10">
        <input type="button" value="Create" class="btn btn-default" id="UseShipAddr" />
   </div>
</div>

AJAX

$('#UseShipAddr').click(function () {
        var formData = new FormData();
        var totalFiles = document.getElementById("FileUpload").files.length;
        for (var i = 0; i < totalFiles; i++) {
            var file = document.getElementById("FileUpload").files[i];

            formData.append("IMG", file);
            alert("h" + file);
        }
        formData.append("name", "James");
        formData.append("age", "1");

        $.ajax({
            url: "/Post/New",
            type: "POST",
            data: formData,
            cache: false,
            async: true,
            success: function (data) {
                alert(data);
            }
        });
    });

控制器

[HttpPost]
//[ValidateAntiForgeryToken]
public async Task<ActionResult> New([Bind(Include="age","name","IMG")] POST rec)
{
   if (ModelState.IsValid)
      {
         db.REC.Add(rec);
         await db.SaveChangesAsync();
         return RedirectToAction("My", "Post");
      }
   return View(rec);
}

2 个答案:

答案 0 :(得分:0)

在查询字符串中发送额外参数。这是AJAX代码:

$.ajax({
    url: "/Post/New?name=James&age=1",
    type: "POST",
    data: formData,
    cache: false,
    async: true,
    contentType: false, // Not to set any content header  
    processData: false, // Not to process data  
    success: function (data) {
        alert(data);
    }
});

您的控制器应类似于以下内容:

public async Task<ActionResult> New(string name, int age)
{
    try
    {
        foreach (string file in Request.Files)
        {
            var fileContent = Request.Files[file];
            if (fileContent != null && fileContent.ContentLength > 0)
            {
                // get a stream
                var stream = fileContent.InputStream;
                // and optionally write the file to disk
                var fileName = Path.GetFileName(file);
                using (var fileStream = new MemoryStream())
                {
                    stream.CopyTo(fileStream);
                }

                // File is in the memory stream, do whatever you need to do
            }
        }
    }
    catch (Exception)
    {

        // whatever you want to do
    }
}

答案 1 :(得分:0)

在表单提交#UseShipAddr点击事件中的对象中创建表单时,您没有指定任何表单。请在创建对象时指定您的表单:

var formData = new FormData($(#formID)[0]);

或创建表单构造函数

var dataString = new FormData();

将文件附加到表单

dataString.append("UploadedFile", selectedFile);
var form = $('#formID')[0];
var dataString = new FormData(form);

现在将该字符串发送到控制器中的操作。

您的请求中存在很多问题。首先删除它,然后你就可以调用控制器的那个动作。