简体   繁体   English

使用ajax时asp mvc显示未更新

[英]asp mvc display not updating when using ajax

I have been following the example of some ajax functionality I got working earlier in my project, but I have come to a sticking point where my current functionality doesn't seem to work, the only difference that I can see that I am naming the partialView that I am returning and that I am trying to update images being displayed (although i'm guessing that wont make a difference). 我一直在跟随我在项目中较早使用的一些ajax功能的示例,但是我遇到了一个棘手的问题,即我当前的功能似乎无法正常工作,唯一的区别是我看到的是命名partialView我正在返回并且正在尝试更新正在显示的图像(尽管我猜这不会有所作为)。

Aim Allow user to select and upload images, and display newly uploaded images using ajax 目的允许用户选择和上传图像,并使用ajax显示新上传的图像

Problem Images from both the temporary and final destination folders are displayed on initial page load, but partial page refresh does not appear to happen after upload is complete 问题临时和最终目标文件夹中的图像均在初始页面加载时显示,但上传完成后似乎不会发生部分页面刷新

controller 调节器

[HttpPost]
public ActionResult _Image(TakeOn to, IEnumerable<HttpPostedFileBase> FileUpload)
{
    to.ImageUpload(FileUpload);//takes all files in FileUpload and places them in a temporary folder
    return PartialView("_Rooms", to);
}

js (ajax) js(ajax)

$(".row").on("change", ".imgInput", function (e) {
    var roomID = $(this).siblings("input:hidden").val();
    $("#roomIdentifier").val(roomID);
    var formData = new FormData(jQuery('#takeOn').get(0)) // store form data to pass on to the controller
    $.ajax({
        type: "POST",
        url: "/Property/_Image",
        contentType: false,
        data: formData,
        dataType: 'json',
        encode: true,
        async: false,
        processData: false,
        cache: false,
        success: function (data) {
            //$(".imgUploader").html(data);//first attempt, both tried by targetting .imgUploader and #accordion
            $("#accordion").replaceWith(("#accordion", html));
        },
        error: function (request, status, error) {
        }
    });

    //clear input value
    var input = $(this);
    input.replaceWith(input.val('').clone(true));
    //clear identifier
    $("#roomIdentifier").val('');
});

view (_Rooms.cshtml) - (this is a partial view which is held in #accordion div ) 视图(_Rooms.cshtml)-(这是#accordion div中保存的局部视图)

@model TjsPropertyPeople.Web.Admin.ViewModels.Property.TakeOn

@for (int i = 0; i < Model.Rooms.Count; i++)
{
<div class="panel panel-default room">
    <div class="panel-heading">
        <h4 class="panel-title">
            @{ ViewBag.Title = Model.Rooms[i].Title == null ? "New Room" : Model.Rooms[i].Title; }
            @{ ViewBag.titleID = "title" + i; }
            <a id=@ViewBag.titleID data-toggle="collapse" data-parent="#accordion" href="#collapseOne" class="collapsed">@ViewBag.Title</a>
        </h4>
    </div>
    <div class="panel-collapse collapse in" style="height: auto;">
        <div class="panel-body">
            <row class="col-lg-4">
                @{ViewBag.roomID = "roomtitle" + i;}
                @Html.TextBoxFor(m => m.Rooms[i].Title, null, new { @id = ViewBag.roomID, @class = "form-control roomTitle", @placeholder = "Title" })
            </row>
            <row class="col-lg-4">
                @Html.TextBoxFor(m => m.Rooms[i].Width, null, new { @class = "form-control", @placeholder = "Width" })
            </row>
            <row class="col-lg-4">
                @Html.TextBoxFor(m => m.Rooms[i].Length, null, new { @class = "form-control", @placeholder = "Length" })
                <label class="checkbox-inline">
                    @Html.CheckBoxFor(m => Model.Rooms[i].Overall) Overall
                </label>
            </row>
            <row class="col-lg-6">
                @Html.TextAreaFor(m => m.Rooms[i].Description, new { @class = "form-control", @placeholder = "Description" })
            </row>
            <row class="col-lg-6">
                <div class="imgUploader">
                    <div>
                        <div style="height: auto; width: auto; position: relative;">
                            @{ ViewBag.TempPath = Server.MapPath("~/App_Uploads/Images/Temp/" + Model.PropertyID + "/" + Model.Rooms[i].RoomID + "/"); }
                            @{ ViewBag.UploadedPath = Server.MapPath("~/App_Uploads/Images/Property/" + Model.PropertyID + "/" + Model.Rooms[i].RoomID + "/"); }
                            @{ ViewBag.TempExists = Directory.Exists(ViewBag.TempPath); }
                            @{ ViewBag.UploadedExists = Directory.Exists(ViewBag.UploadedPath); }
                            @{ List<string> files = new List<string>(); }

                            @if (ViewBag.TempExists)
                            {
                                string[] f = Directory.GetFiles(ViewBag.TempPath);
                                files.AddRange(f);
                            }
                            @if (ViewBag.UploadedExists)
                            {
                                string[] f = Directory.GetFiles(ViewBag.UploadedPath);
                                files.AddRange(f);
                            }
                            @foreach (var file in files)
                            {
                                string name = file.Substring(file.LastIndexOf("App_Uploads"));
                                name = @"~\" + name;
                                <img class="pull-left panel" src="@Url.Content(name)" height="50" />
                                @*<div class="delete">X</div>*@
                            }
                        </div>
                    </div>
                </div>
                <input class="imgInput" type="file" name="FileUpload" multiple accept="image/jpeg">
                @Html.HiddenFor(m => m.Rooms[i].RoomID)
            </row>
        </div>
    </div>
</div>
}

Note I realise that the view could be written MUCH better, I just don't know how to abstract all that unnecessary code from the view at this time and feel I should get the functionality working before "playing" with yet another area I don't fully understand (although I'm against any advice that can be offered in this area) 请注意,我意识到可以更好地编写视图,但我不知道此时该如何从视图中提取所有不必要的代码,因此我觉得在“玩”我不喜欢的另一个区域之前,我应该使功能正常工作不能完全理解(尽管我反对这方面可以提供的任何建议)

EDIT 编辑

in the error part of the script I added alert("Error: " + error) and it returned this 在脚本的错误部分,我添加了alert("Error: " + error)并返回了

javascript error syntax: unexpected token <

I have googled it and found this answer , there seem to be a lot of places in my code that could be causing this (if this answer is applicable to me). 我已经用谷歌搜索并找到了这个答案 ,我的代码中似乎有很多地方可能导致这个问题(如果这个答案适用于我)。 So how would I start tracking down the root of the problem? 那么,我将如何开始追踪问题的根源?

Try changing this line in your $ajax.success function from: 尝试从以下位置更改$ajax.success函数中的这一行:

$("#accordion").replaceWith(("#accordion", html));

To: 至:

 $("#accordion").html(data);

The ("#accordion", html) looks like invalid jQuery to me, and I don't see a var called html in your code either. ("#accordion", html)在我看来像是无效的jQuery,在您的代码中也没有看到称为html ("#accordion", html) Your partial HTML response var is named data not html . 您的部分HTML响应变量名为data而不是html

If that doesn't work, add the following line to your $ajax.success function: 如果那不起作用,请将以下行添加到$ ajax.success函数中:

console.log(data);

And see that the response is your Partial HTML in your browser F12 developer tools Console 并在浏览器F12开发人员工具Console看到响应是您的部分HTML

Thanks to Brian Ogden I was able to resolve this issue. 感谢Brian Ogden,我得以解决此问题。

As mentioned I needed to change 如前所述,我需要改变

$("#accordion").replaceWith(("#accordion", html));

To: 至:

$("#accordion").html(data);

But this brought another problem syntax error: unexpected token < 但这带来了另一个问题syntax error: unexpected token <

It was caused by not closing a html tag so changing: 这是由于未关闭html标签而导致的:

<input class="imgInput" type="file" name="FileUpload" multiple accept="image/jpeg">

to

<input class="imgInput" type="file" name="FileUpload" multiple accept="image/jpeg" />

resolved it completely. 彻底解决了。 I would be interested to know why a badly formatted tag stop ajax calls from working 我想知道为什么格式错误的标签会阻止ajax调用正常工作

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

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