简体   繁体   中英

Getting always an error while using Jquery Ajax Post Method in C# MVC

I am trying to use ajax in my view in order to update changes in users profiles. Unfortunately, whatever I try, I get the error message "Error!!!". I think the problem is my model, and I have tried to customize it, but it still does not work.

Here is the JS that is executed when the user pushes the "save" button:

$(document.getElementById('save')).on("click", function() {
            var liSportMotives = $('#sortable li').map(function(i, n) {
                return $(n).attr('id');
            }).get();
            var liActivities = $('#myCarousel div').map(function(i, n) {
                if ($(n).hasClass('thumbnailActive')) {
                    return $(n).attr('id');
                }
            }).get();
            var myPostJSONObject = {
            Weight : parseFloat($(document.getElementById('weightrange')).val()).toFixed(1),
            Height : parseFloat($(document.getElementById('heightrange')).val()).toFixed(2),
            IsSportsBeginnerPractise : $("input:radio[name='IsSportsBeginnerPractise']:checked").val(),
            IsSportsBeginnerKnowledge : $("input:radio[name='IsSportsBeginnerKnowledge']:checked").val(),
            IsNutritionBeginnerPractise : $("input:radio[name='IsNutritionBeginnerPractise']:checked").val(),
            IsNutritionBeginnerKnowledge : $("input:radio[name='IsNutritionBeginnerKnowledge']:checked").val(),
            NewSportMotives : liSportMotives,
            NewActivities : liActivities
        };
            $.ajax({
                url: '@Url.Action("ManageConfirmation", "Account")',
                type: "POST",
                traditional: true,
                data: JSON.stringify(myPostJSONObject),
                dataType: "json",
                contentType: "application/json; charset=utf-8",
                success: function (data) {
                    alert("Success!");
                },
                error: function () {
                    alert("Error!!!");
                }
            });
        });

My model in my controller looks like this:

public class ManageUserDetails
        {
            public decimal Height { get; set; }

            public decimal Weight { get; set; }

            public bool IsSportsBeginnerPractise { get; set; }

            public bool IsSportsBeginnerKnowledge { get; set; }

            public bool IsNutritionBeginnerPractise { get; set; }

            public bool IsNutritionBeginnerKnowledge { get; set; }

            public String[] NewSportMotives { get; set; }

            public String[] NewActivities { get; set; }
        }

And I have an action that looks like this:

    public ActionResult ManageConfirmation(ManageUserDetails model)
    {
        return RedirectToAction("Index", "Home");
    }

Your action is attemting to redirect due to return RedirectToAction("Index", "Home"); .

This will result in some unexcpected issues.

You can try this:

[HttpPost]
public JsonResult ManageConfirmation(ManageUserDetails model)
{
    //do stuff e.g. save model.
    return Json(new { data = "some data to send back" }, JsonRequestBehavior.AllowGet);
}

You should not redirect to any in an Ajax call. Instead use the following :

public ActionResult ManageConfirmation(ManageUserDetails model)
    {
        return Json(new { data = "true" }, JsonRequestBehavior.AllowGet);
    }

and in the Ajax call :

$.ajax({
                url: '@Url.Action("ManageConfirmation", "Account")',
                type: "POST",
                traditional: true,
                data: JSON.stringify(myPostJSONObject),
                dataType: "json",
                contentType: "application/json; charset=utf-8",
                success: function (data) {
                window.location.href = '@Url.Action("Index","Home")';
                    alert("Success!");
                },
                error: function () {
                    alert("Error!!!");
                }
            });

See the success method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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