Wednesday, 19 December 2018

MVC - JSON - Fix Issue - Function in Controller not receiving data





Function in controller is called but not receiving data

Watch this example on YouTube




to fix it replace

  function AddUser(e) {
            var UserRec = {};
            UserRec.UserFirstName = $('#FirstName').val();
            UserRec.UserLastName = $('#LastName').val();
            $.ajax({
                url: '@Url.Action("SaveUser", "Home")',
                data: '{usr: ' + JSON.stringify(UserRec) + '}',
                contentType: 'application/json; charset=utf-8',
                dataType: 'json',
                success: function (response) {
                    if (response.ErrorMessage != null) {
                        alert(response.ErrorMessage);
                    }
                    else {
                        window.location.href = response.Url;
                    }
                },
                error: function (xhr, status, error) {
                    var el = document.createElement('html');
                    el.innerHTML = xhr.responseText;
                    alert(el.getElementByTagName('title')[0].innerText);
                }
           
            });

with

  function AddUser(e) {
            var UserRec = {};
            UserRec.UserFirstName = $('#FirstName').val();
            UserRec.UserLastName = $('#LastName').val();
            $.ajax({
                url: '@Url.Action("SaveUser", "Home")',
                type: 'POST',
                data: '{usr: ' + JSON.stringify(UserRec) + '}',
                contentType: 'application/json; charset=utf-8',
                dataType: 'json',
                success: function (response) {
                    if (response.ErrorMessage != null) {
                        alert(response.ErrorMessage);
                    }
                    else {
                        window.location.href = response.Url;
                    }
                },
                error: function (xhr, status, error) {
                    var el = document.createElement('html');
                    el.innerHTML = xhr.responseText;
                    alert(el.getElementByTagName('title')[0].innerText);
                }
           
            });

No comments:

Post a Comment