异步添加/更新保存方法未更新

Asynchronous Add/Update save method not updating

本文关键字:更新 方法 保存 异步 添加      更新时间:2023-09-26

我正在为一个项目构建一个 .NET 页面,该页面为新用户添加新的城市和州,或者更新城市和州(如果他们的 ID 已在数据库中)。一切都运行正常,除了如果过去的用户单击提交以更新其信息,则会将一个全新的条目添加到数据库中。

我已经在下面列出的存储库中创建了该方法。

public async Task<LocationViewModel> SaveLocationAsync(LocationViewModel model)
    {
        try
        {
            var location = new Location()
            {
                City = model.City,
                State = model.State
            };
            if (model.Id != 0)
            {
                location.Id = model.Id;
            }
            _dbcontext.Location.AddOrUpdate(location);
            await _dbcontext.SaveChangesAsync();
            return model;
        }
        catch (Exception ex)
        {
            model.Error = true;
            model.ErrorMessages = new List<string>()
            {
                string.Format("Something went wrong - Message: {0} 'n Stack Trace: {1}", ex.Message,
                    ex.StackTrace)
            };
            return model;
        }
    }

我还构建了一个控制器,用于异步保存和更新如下所示的现有记录。

[System.Web.Mvc.AllowAnonymous]
        [System.Web.Http.HttpPost]
        public async Task<LocationViewModel> SaveLocationApiAsync(LocationViewModel model)
        {
            var result = new LocationViewModel();
            if (ModelState.IsValid)
            {
                result = await _locationRepository.SaveLocationAsync(model);
            }
            return result;
        }

此外,我还添加了我所有的路线和参考。

为什么将新条目放入数据库中而不是更新当前条目?Javascript如下所示。

self.Submit = function () {
            if (self.errors().length !== 0) {
                self.errors.showAllMessages();
                return;
            }
            if (isNumber(locationId)) {
                self.Location().LocationId(locationId);
                swal("Success", "Thank you for your submission 'nYour information has been updated.", "success");
            }
            var newData = ko.mapping.toJSON(self.Location());
            var url = "/Admin/SaveLocationApiAsync/Post/";
            $.ajax({
                url: url,
                method: "POST",
                data: newData,
                contentType: 'application/json; charset=utf-8',
                dataType: 'json',
                success: function (result) {
                    if (result.Error === true) {
                        swal("Error", result.ErrorMessages.join(''n'), "error");
                    } else {
                        //TOdo
                    }
                },
                error: function () {
                    swal("Error", "Something went wrong.'nPlease contact help.", "error");
                }
            });
        };

如果很多,我深表歉意。我已经反复检查了所有内容并修复了所有错误。我没主意了。

提前谢谢。

您的 url 查找控制器操作似乎不正确。您必须var url = "/Admin/SaveLocationApiAsync/Post/";何时应该var url = "/Admin/SaveLocationApiAsync";

获取正确 url 的另一种方法是:

var url = '@Url.Action("SaveLocationApiAsync", "<ControllerName>")';

此外,在 ajax 错误处理程序中,您可以获取 HTTP 状态代码和错误消息,这将有所帮助。

error: function (jqXHR, textStatus, errorThrown) {
                    swal("Error", "Something went wrong.'nPlease contact help.", "error");
                }

编辑:

我应该先说,当你的JavaScript在一个视图中时,使用Url.Action是有效的(在这种情况下假设Razor视图)。

Fiddler 是调试 ajax 调用时使用的好工具。