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

时间:2016-01-23 22:58:01

标签: javascript c# asp.net-mvc visual-studio

我正在为一个项目构建一个.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");
                }
            });
        };

如果它很多,我道歉。我已反复检查所有内容并修复了所有错误。我没有想法。

提前致谢。

1 个答案:

答案 0 :(得分:0)

您的网址看起来控制器操作似乎不正确。如果var url = "/Admin/SaveLocationApiAsync/Post/";

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

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

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

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

public class EnemyPatrol : MonoBehaviour {

    public float moveSpeed;
    public bool moveRight;

    public float wallCheckRadius;
    public Transform wallCheck;
    public LayerMask whatIsWall;
    private bool hittingWall;

    private bool notAtEdge;
    public Transform edgeCheck;

    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void Update () {
        //GetComponent<Rigidbody2D> ().velocity=new Vector2(3,0);
        //Debug.Log("Premikam se desno   "+GetComponent<Rigidbody2D> ().velocity);

        //hittingWall = Physics2D.OverlapCircle (wallCheck.position, wallCheckRadius, whatIsWall);
        wallCheckRadius = 0.6f;
        notAtEdge = Physics2D.OverlapCircle (edgeCheck.position, wallCheckRadius, whatIsWall);


        hittingWall = false;
        //notAtEdge = true;
        if (hittingWall || !notAtEdge) {
            moveRight = !moveRight;
            Debug.Log ("Zadene steno " + hittingWall + "  Ni na robu  " + notAtEdge);
        }
        // Prepreci krozenje igralca ( zabavna zadeva )
        GetComponent<Rigidbody2D>().constraints = RigidbodyConstraints2D.FreezeRotation;

        if (moveRight) {
            transform.localScale = new Vector3 (1f, 1f, 1f);
            GetComponent<Rigidbody2D> ().velocity=new Vector2(3,0);
            Debug.Log("Premikam se desno   "+GetComponent<Rigidbody2D> ().velocity);
        } else {
            transform.localScale = new Vector3 (-1f, 1f, 1f);
            GetComponent<Rigidbody2D> ().velocity=new Vector2(-3,0);
            Debug.Log("Premikam se levo"+GetComponent<Rigidbody2D> ().velocity);
        }
    }
}

修改

我应该预先知道当你的JavaScript在视图中时使用Url.Action(在这种情况下假设是Razor视图)。

调试ajax调用时,

Fiddler是一个很好的工具。