【问题标题】:FileUpload in Ajax Form in ASP.NET MVC Partial View Not WorkingASP.NET MVC 部分视图中的 Ajax 表单中的文件上传不起作用
【发布时间】:2014-01-03 17:53:49
【问题描述】:

我有 2 个文件上传,用于在从用户个人资料页面调用的部分视图中编辑用户个人资料。问题是动作方法中的HttpPostedFileBase参数总是null

当我在个人资料页面之外调用此部分视图并且没有布局时,文件上传已成功完成并将文件发送到操作方法。

这是我在控制器中的操作方法:

[AcceptVerbs(HttpVerbs.Post)]
[Authorize(Roles = "User")]
public ActionResult EditProfile(ProfileGeneralDescription editedModel,
                                   HttpPostedFileBase imageFile,
                                   HttpPostedFileBase coverFile)
{
         //Some code here...   
}

这是我的部分观点cshtml代码:

@model Website.Models.ViewModel.Profile

@using (Ajax.BeginForm("EditProfile", "Profile", new { postOwnerUser = User.Identity.Name }, new AjaxOptions()
{
    HttpMethod = "POST",
    InsertionMode = InsertionMode.Replace,
    UpdateTargetId = "GeneralSection"
}, new { enctype = "multipart/form-data" }))
{

    <div>
        <button type="submit" name="Save" class="btn btn-default btn-xs">Save Changes</button>
        @Ajax.ActionLink("Cancel", "ProfileDescription", "Profile",
            new {username = Model.Username, type = "Show"},
            new AjaxOptions()
            {
                HttpMethod = "GET",
                InsertionMode = InsertionMode.Replace,
                UpdateTargetId = "GeneralSection"
            },
            new {@class = "btn btn-default btn-xs"})
    </div>

    <input type="hidden" name="username" id="username" value="@Model.Username"/>

    <fieldset>
        <legend>Edit Photos</legend>
        <div>
            Select profile picture:
            <input id="imageFile" type="file" name="imageFile" accept="image/png, image/jpeg" />
            @Html.CheckBoxFor(modelItem => modelItem.DefaultCover)<span>Remove profile photo</span>
        </div>
        <div>
            Select cover picture:
            <input id="coverFile" type="file" name="coverFile" accept="image/png, image/jpeg" />
            @Html.CheckBoxFor(modelItem => modelItem.DefaultCover)<span>RemoveCover</span>
        </div>
    </fieldset>
}

我的错误在哪里?
提前致谢。

【问题讨论】:

  • 你需要[HttpPost]属性吗?
  • 我忘记复制这些代码了。请查看我的更新。
  • 你能给出代码显示当局部视图不工作时你是如何调用它的吗?
  • 这是我的操作链接:@Ajax.ActionLink("Edit Profile", "ProfileGeneralDescription", "Profile", new { username = Model.Username, type = "Edit" }, new AjaxOptions() { HttpMethod = "GET", InsertionMode = InsertionMode.Replace, UpdateTargetId = "GeneralSection" }, new { @class = "btn btn-default btn-xs" } )
  • 我找到了这篇文章:mvc3 file upload using ajax form - Request.Files empty,最佳答案是 Ajax 表单不支持文件上传。我该怎么做才能编辑用户资料?

标签: c# asp.net-mvc asp.net-mvc-4 file-upload ajaxform


【解决方案1】:

文件上传通常使用简单的表单发布来启动。如果要使用 AJAX 发起上传,则需要编写一些 javascript 来使用 XmlHttpRequest (XHR) 对象,如下所示(使用 jQuery):

<script>
    function submit (e){
        e.preventDefault = true;
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function(e) {
            if ( 4 == this.readyState ) {
                console.log(['xhr upload complete', e]);
            }
        };
        xhr.open('post', 'Profile/EditProfile', true);
        xhr.setRequestHeader("Content-Type","multipart/form-data");
        var formData = new FormData();
        formData.append("imageFile", $("#imageFile").files[0]);
        formData.append("coverFile", $("#coverFile").files[0]);
        // etc
        xhr.send(formData);
    };
</script>

请注意,您使用表单元素中的值在代码中填充 javascript FormData 对象。然后将此函数连接到提交按钮的点击事件:

    <button type="button" name="Save" onclick="submit()" class="btn btn-default btn-xs">Save Changes</button>

您还可以删除视图中的 Ajax 表单,因为使用此方法时不需要它。

【讨论】:

  • 干得好!谢谢@Paul :-)
  • 如何用这个块替换返回的局部视图? (如 AjaxOptions 中的 Ajax.BeginForm() )。 beginForm 函数中的当前选项不起作用!
  • 控制器方法返回的更新数据是否需要显示?
  • 如果这样做,您可以像这样从 XHR 对象获取服务器响应:xhr.responseText 或 xhr.responseXML。然后,您的脚本需要将其应用于相关的 html 元素。
  • 是的,我按照你说的做。但是个人资料页面消失了,返回的部分视图显示在浏览器中。此脚本不会替换任何内容,并且在发布数据后似乎无法正常工作。
猜你喜欢
  • 1970-01-01
  • 2012-11-08
  • 2016-10-15
  • 2014-05-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-23
  • 1970-01-01
相关资源
最近更新 更多