简体   繁体   English

部分视图未在 ajax 上更新成功后 function

[英]Partial View not updating on ajax post success function

I am currently trying to create a system that will display uploaded images(s) from a file input to a div in my view.我目前正在尝试创建一个系统,该系统将在我的视图中显示从文件输入到 div 的上传图像。 (and have plans to add support for documents later) (并计划稍后添加对文档的支持)

The problem is that the partial view does not seem to be updating when I use an onchange function for the file input to pass the image(s) to my partial view that should be re-loaded into a div in my view and display the images.问题是当我使用 onchange function 作为文件输入以将图像传递给我的部分视图时,部分视图似乎没有更新,该部分视图应该重新加载到我视图中的 div 中并显示图像.

I know that the partial view loads the first time, because of the onload function that alerts me when the div is loaded is doing nothing after the initial page load.我知道部分视图是第一次加载,因为加载 function 会在加载 div 时提醒我在初始页面加载后什么都不做。

I know the request is being sent because when I try to perform a console.log or other actions inside the success function of the ajax call, they all work properly.我知道正在发送请求,因为当我尝试在 ajax 调用的成功 function 中执行 console.log 或其他操作时,它们都可以正常工作。

My view:我的观点:

<div>
<h3>Attach File(s) (optional):</h3>
<form enctype="multipart/form-data">
    <input id="fileInput" onchange="addFile()" type="file" accept="image/png, image/gif, image/jpeg, .pdf, .doc" /> 
</form>
    <br />
    <br />
    <img width="750" style="display:none" id="UploadedImage" src="#" />
    <div id="fileDiv">
        <partial name="~/Views/Shared/_FilePreviewPartial.cshtml" />
    </div>
</div>

My javascript function:我的 javascript function:

function addFile() {

    var input = document.getElementById("fileInput");
    var files = input.files;
    var formData = new FormData();

    for (var i = 0; i != files.length; i++) {
        formData.append("files", files[i]);
    }

    $.ajax(
        {
            url: "/RODispositions/UpdateFilePreview/",
            data: formData,
            processData: false,
            contentType: false,
            type: "POST",
            success: function (data) {
                $("#fileDiv").html(data);
                console.log("posted");
            }
        }
    );
}

My partial view:我的部分观点:

<body onload="console.log('refreshed file div')">
<div>
@foreach(var image in @Model.RODImages)
{
    <img width="750" id="UploadedImage" src="#" />
    <br />
    <a href="#">Remove</a>
}

@foreach(var document in @Model.RODDocuments)
{
    <a href="">Download file</a>
    <br />
    <a href="#">Remove</a>
}
</div>
</body>

My controller method:我的 controller 方法:

    [HttpPost]
    public PartialViewResult UpdateFilePreviewAsync(ICollection<IFormFile> files)
    {
        var vm = new ViewModel()
        {
            RODImages = new List<byte[]>(),
            RODDocuments = new List<byte[]>()
        };

        foreach (var file in files)
        {
            if (file.Length > 0)
            {
                using (var ms = new MemoryStream())
                {
                    file.CopyTo(ms);
                    var fileBytes = ms.ToArray();
                    vm.RODImages.Append(fileBytes);
                }
            }
        }

        return PartialView("_FilePreviewPartial", vm);
    }

The partial is being loaded the first time that I load the page, but is not being loaded again after the ajax call.第一次加载页面时正在加载部分内容,但在 ajax 调用之后不再加载。 I have made similar functions that have loaded a PartialViewResult into a div with no issues before, but have no idea why this is not working.我已经制作了类似的函数,将 PartialViewResult 加载到 div 中之前没有问题,但不知道为什么这不起作用。 Bear in mind that I am still new to .NET programming, so any help and/or explanation would be appreciated.请记住,我仍然是 .NET 编程的新手,因此将不胜感激任何帮助和/或解释。

Change the Action name UpdateFilePreviewAsync to UpdateFilePreview;将 Action 名称 UpdateFilePreviewAsync 更改为 UpdateFilePreview;

    [HttpPost]
    public IActionResult UpdateFilePreview(ICollection<IFormFile> files)
    {
        var vm = new ViewModel()
        {
            RODImages = new List<byte[]>(),
            RODDocuments = new List<byte[]>()
        };

        foreach (var file in files)
        {
            if (file.Length > 0)
            {
                using (var ms = new MemoryStream())
                {
                    file.CopyTo(ms);
                    var fileBytes = ms.ToArray();
                    vm.RODImages.Add(fileBytes);
                }
            }
        }

        return PartialView("_FilePreviewPartial", vm);

    }

After doing what LajosArpad suggested and attempting to update the div to display a string in the ajax success function instead of the partial view I was trying to load, the file div did update.在执行LajosArpad建议并尝试更新 div 以在 ajax 成功 function 而不是我尝试加载的部分视图中显示字符串之后,文件 div 确实更新了。 Meaning that the issue was with the ActionResult being passed back to the ajax success function.这意味着问题在于 ActionResult 被传递回 ajax 成功 function。 After going back though my controller code I found the issue to be that I had been trying to add each image to the list with the List.Append function instead of the List.Add function and that was somehow messing with the data that was returned, and changing the List.Append to List.Add allowed the partial view to be loaded properly. After going back though my controller code I found the issue to be that I had been trying to add each image to the list with the List.Append function instead of the List.Add function and that was somehow messing with the data that was returned,并将List.Append更改为List.Add允许正确加载部分视图。

The partial is being loaded the first time that I load the page, but is not being loaded again after the ajax call.第一次加载页面时正在加载部分内容,但在 ajax 调用之后不再加载。

Firstly, it should be vm.RODImages.Add(fileBytes);首先,它应该是vm.RODImages.Add(fileBytes); instead of .Append() .而不是.Append()

Then, your partial view even does not set the image src by the byte array .然后,您的局部视图甚至没有按字节数组设置图像 src

Besides, it seems you want to post multiple files, be sure add multiple attribute in your input like below:此外,您似乎想发布多个文件,请确保在您的输入中添加multiple属性,如下所示:

<input id="fileInput" multiple  onchange="addFile()" type="file" accept="image/png, image/gif, image/jpeg, .pdf, .doc"/> 

Here is a simple demo:这是一个简单的演示:

[HttpPost]
public PartialViewResult UpdateFilePreviewAsync(ICollection<IFormFile> files)
{
    var vm = new ViewModel()
    {
        RODImages = new List<byte[]>(),
        RODDocuments = new List<byte[]>()
    };

    foreach (var file in files)
    {
        if (file.Length > 0)
        {
            using (var ms = new MemoryStream())
            {
                file.CopyTo(ms);
                var fileBytes = ms.ToArray();
                vm.RODImages.Add(fileBytes);
            }
        }
    }

    return PartialView("_FilePreviewPartial", vm);
}

Partial View:局部视图:

@model ViewModel
<body onload="console.log('refreshed file div')">
<div>
@foreach(var image in @Model.RODImages)
{
                                           //modify here...
    <img width="750" id="UploadedImage" src="data:image/png;base64, @Convert.ToBase64String(image)" />           
    <br />
    <a href="#">Remove</a>
}

@foreach(var document in @Model.RODDocuments)
{
    <a href="">Download file</a>
    <br />
    <a href="#">Remove</a>
}
</div>
</body>

Note:笔记:

If your image format are all different , I think you need modify your ViewModel like below:如果您的图像格式都不同,我认为您需要修改您的 ViewModel,如下所示:

Model: Model:

public class ViewModel
{
    public List<RODImages> RODImages { get; set; }
    public List<RODDocuments> RODDocuments { get; set; }
}
public class RODImages
{
    public byte[] RODImage { get; set; }
    public string Format { get; set; }
}
public class RODDocuments
{
    public byte[] RODDocument { get; set; }
    public string Format { get; set; }
}

Controller: Controller:

[HttpPost]
public PartialViewResult UpdateFilePreviewAsync(ICollection<IFormFile> files)
{
    var vm = new ViewModel()
    {
        RODImages = new List<RODImages>(),
        RODDocuments = new List<RODDocuments>()
    };

    foreach (var file in files)
    {
        if (file.Length > 0)
        {
            using (var ms = new MemoryStream())
            {
                file.CopyTo(ms);
                var fileBytes = ms.ToArray();
                vm.RODImages.Add(new RODImages() { RODImage= fileBytes ,Format=file.ContentType});
            }
        }
    }

    return PartialView("_FilePreviewPartial", vm);
}

Partial View:局部视图:

@model ViewModel
<body onload="console.log('refreshed file div')">
<div>
@foreach(var image in @Model.RODImages)
{
                                             //modify here........
    <img width="750" id="UploadedImage" src="data:@image.Format;base64, @Convert.ToBase64String(image.RODImage)" />
    <br />
    <a href="#">Remove</a>
}

@foreach(var document in @Model.RODDocuments)
{
    <a href="">Download file</a>
    <br />
    <a href="#">Remove</a>
}
</div>
</body>

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

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