简体   繁体   English

Ajax文件上传后如何从部分更新模型?

[英]How to update Model from partial after ajax file upload?

So I have ajax file upload partial (using Jquery Form plugin), it's working perfectly, but I don't know to update model value after file uploading 所以我有部分ajax文件上传(使用Jquery Form插件),它工作正常,但是文件上传后我不知道更新模型值

<div>
   @Html.Partial("PhotoUpload", Model.Place)
</div>

Here I'm calling partial and giving to it part of a model. 在这里,我称部分模型为模型的一部分。

@model PlaceMap.DAL.Entities.Place
@using (Html.BeginForm("PhotoUpload", "Place", FormMethod.Post, new { @id = "photoUpload", enctype = "multipart/form-data" }))
{
    {
        @Html.ValidationSummary(true, "Image upload was unsuccessful")
        @Html.HiddenFor(m => m.Photo)                                                                                                                                                                                  
        <input type="file" id="file" name="file"/>
        <input type="submit" id="sbm" />
    }
}

This is view code of partial, accepting model and form for uploading 这是部分,接受模型和上载表格的查看代码

var options = {
    url: "/Place/PhotoUpload",
    dataType: "json",
    clearForm: true,
    resetForm: true,
    success: showResponse
};

function showResponse(responseText, statusText, xhr, $form)
{
    $('#photo').append('<img src="/Images/Places/' + responseText.Photo + '" />');
}

$('#photoUpload').submit(function ()
{
    $('#photoUpload').ajaxSubmit(options);
    return false;
});

Javascript code for plugin 插件的Java代码

    [Authorize]
    [HttpPost]
    public ActionResult PhotoUpload(string Photo, HttpPostedFileBase file)
    {
        try
        {
            using (var ms = new MemoryStream())
            {
                //some logic here
                return Json(new { Photo = filename });
            }

        }
        catch (ArgumentException)
        {

        }

        return PartialView();
    }

Controller action code. 控制器动作代码。 It's returning file name, it's going to js function "showResponse" and appending image to div. 它返回文件名,然后转到js函数“ showResponse”,并将图像附加到div。 It's all work perfectly, but I have to write file name to @Model.Photo of this partial and I don't know how to do it. 一切都很好,但是我必须将文件名写入@ Model.Photo部分的照片,我不知道该怎么做。 Any suggestions? 有什么建议么?

One possibility is to use text/plain from the server: 一种可能性是使用服务器上的text/plain

return Json(new { Photo = filename }, "text/plain");

and on the client manually parse: 并在客户端上手动解析:

function showResponse(responseText, statusText, xhr, $form) {
    var data = $.parseJSON(responseText);
    $('#photo').append('<img src="/Images/Places/' + data.Photo + '" />');
}

Obviously you lust remove the dataType: 'json' option for this to work. 显然,您渴望删除dataType: 'json'选项以使其正常工作。

Another possibility is to follow what's explained in the documentation and write a custom action result which will wrap your JSON response with the <textarea> tags: 另一种可能性是遵循文档中的解释并编写自定义操作结果,该结果将使用<textarea>标签包装您的JSON响应:

Browsers that support the XMLHttpRequest Level 2 will be able to upload files seamlessly and even get progress updates as the upload proceeds. 支持XMLHttpRequest级别2的浏览器将能够无缝上传文件,甚至可以在上传过程中获得进度更新。 For older browsers, a fallback technology is used which involves iframes since it is not possible to upload files using the level 1 implmenentation of the XMLHttpRequest object. 对于较旧的浏览器,由于无法使用XMLHttpRequest对象的1级实现上载文件,因此使用了涉及iframe的后备技术。 This is a common fallback technique, but it has inherent limitations. 这是一种常见的后备技术,但是它具有固有的局限性。 The iframe element is used as the target of the form's submit operation which means that the server response is written to the iframe. iframe元素用作表单提交操作的目标,这意味着服务器响应已写入iframe。 This is fine if the response type is HTML or XML, but doesn't work as well if the response type is script or JSON, both of which often contain characters that need to be repesented using entity references when found in HTML markup. 如果响应类型为HTML或XML,则很好,但如果响应类型为脚本或JSON,则效果不佳,这两种脚本通常都包含在HTML标记中找到时需要使用实体引用来表示的字符。

To account for the challenges of script and JSON responses when using the iframe mode, the Form Plugin allows these responses to be embedded in a textarea element and it is recommended that you do so for these response types when used in conjuction with file uploads and older browsers. 为了解决使用iframe模式时脚本和JSON响应的挑战,表单插件允许将这些响应嵌入到textarea元素中,建议结合使用文件上传和更早版本时对这些响应类型进行嵌入浏览器。 Please note, however, that if there is no file input in the form then the request uses normal XHR to submit the form (not an iframe). 但是请注意,如果表单中没有文件输入,那么请求将使用普通XHR提交表单(不是iframe)。 This puts the burden on your server code to know when to use a textarea and when not to. 这给您的服务器代码增加了负担,使您知道何时使用文本区域,何时不使用文本区域。 If you like, you can use the iframe option of the plugin to force it to always use an iframe mode and then your server can always embed the response in a textarea. 如果愿意,可以使用插件的iframe选项强制其始终使用iframe模式,然后服务器始终可以将响应嵌入文本区域。 But the recommended solution is to test for the 'X-Requested-With' request header. 但是推荐的解决方案是测试“ X-Requested-With”请求标头。 If the value of that header is 'XMLHttpRequest' then you know that the form was posted via ajax. 如果该标头的值为“ XMLHttpRequest”,则您知道该表单是通过ajax发布的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM