2

我已经在 mvc3 中正常提交了一个文件。现在我需要对 Ajax 做同样的事情。所以我使用了这个 jquery 插件:http: //jquery.malsup.com/form/#ajaxSubmit

查看代码:

$(document).ready(function () {
        var options = {
            url: "/Home/TakeFile",
            dataType: "json",
            success: showResponse
        };


        $("#File").submit(function () {
            alert("submit");
            $(this).ajaxSubmit(options);
            return false;
        });
    });


    function showResponse(responseText, statusText, xhr, $form) {
        alert("showResponse");
        alert(responseText.fileName);
    }
</script>

@using (Html.BeginForm("TakeFile", "Home", FormMethod.Post, new { @id = "File", enctype = "multipart/form-data" }))
{
    <input type="file" id="file" />
    <input type="submit" value="Click to submit" id="button" />
}

控制器代码:

[HttpPost]
        public ActionResult TakeFile(HttpPostedFileBase file)
        {
            return Json(new { fileName=file.FileName});
        }

我的“TakeFile”方法中的文件参数始终为空。似乎无法使其正常工作。另外,我们可以使用“Ajax.BeginForm()”帮助器吗?

4

4 回答 4

1

AFAIK,您不允许通过 ajax 上传文件...发布文件需要完整的回发。

你需要一个闪存解决方案或类似的东西才能让它发生。例如使用上传...

请参阅此博客文章以使其正常工作

于 2012-04-16T15:52:29.913 回答
1

a 中的html 元素的name属性用于在提交表单后引用表单数据。<input><form>

注意:只有具有 name 属性的表单元素才会在提交表单时传递其值。

由于action方法 public ActionResult TakeFile(HttpPostedFileBase file){..}有一个参数名称'file',在视图中,file输入元素应该有一个name='file'属性。更新代码:

@using (Html.BeginForm("TakeFile", "Home", FormMethod.Post, new { @id = "File", enctype = "multipart/form-data" }))
{
    <input type="file" id="file" name="file" />
    <input type="submit" value="Click to submit" id="button" />
}
于 2012-04-16T19:15:14.367 回答
0

尝试使用以下

<input type="file" id="file" name = "attachment"/>

在您的控制器中添加以下代码以获取文件对象

var file = Request.Files["attachment"];
于 2012-04-16T12:35:47.693 回答
0

上传文件时选项中的dataType:json选项似乎很奇怪,您是否尝试将其删除?

也尝试使用Name输入类型的属性

<input type="file" id="file" name="file" />
于 2012-04-16T15:01:36.630 回答