Share via


Ajax calling > async Task but doesn't load the View

Question

Thursday, March 14, 2019 7:09 PM

Hi All,

I'm calling async Task<ActionResult> from ajax, and its working, I'm calling another view from this Task<ActionResult>, but when the code finish in Task<ActionResult> the view doesn't load, it still in base View.

Ajax:

function Edit(idEmployee) {
            $.ajax({
                url: '@Url.Action("EditEmployee/id","Employees")'.replace('id', idMain),
                type: 'post',
                dataType: 'json',
                contentType: 'application/json;charset=utf-8',
                success: function () {
                },
                error: function (error) {
                    alert(error.statusText);
                }
            });
        }

Code C#

        [HttpPost]
        public async Task<ActionResult> EditEmployee(int id)
        {
            vmEmployee VMemployee = new vmEmployee();
                    Employee emp = new Employee();
                    string apiUrl = ConfigurationManager.AppSettings["baseurl"] + "/EMPLOYEE.API/LoadEmployee";
                    var client = new HttpClient();
                    client.BaseAddress = new Uri(apiUrl);
                    client.DefaultRequestHeaders.Accept.Clear();
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                    HttpResponseMessage responseMessage = await client.PostAsJsonAsync(apiUrl,id);
                    if (responseMessage.IsSuccessStatusCode)
                    {
                        var responseData = responseMessage.Content.ReadAsStringAsync().Result;
                        emp = JsonConvert.DeserializeObject<Employee>(responseData);
                    }
                    VMemployee.Employee= emp;

            return View("NewEmployeePage",VMemployee ); 
        }

Everything it is working fine, and the API working for retrieve object Employee, but this ajax method in View ( Employee List ) when user click on edit, I need to move to View(New Employee)... but it is not working.

By the way I mentioned in ajax > error ( alert(error.statusText)) ..... when code of Task<ActionResult> finish, I found alert > OK ???.    why the ajax going to error but I didn't found any error when I made a debug with the code?

I have one controller > Employee

I have two action method / Views in this controller > 1. EmployeeList which the one has the ajax method.                    2. NewEmployeePage , which I want to move to.

All replies (5)

Thursday, March 14, 2019 8:02 PM âś…Answered

Dear mgebhard,

I tried to write this and it is working now :

 function EditModule(idEmployee) {
alert(idModule);
window.location = '@Url.Action("EditEmployee/id", "Employees")'.replace('id', idEmployee);
}

it is working without ajax !!


Thursday, March 14, 2019 7:17 PM

Khalid Salameh

I'm calling async Task<ActionResult> from ajax, and its working, I'm calling another view from this Task<ActionResult>, but when the code finish in Task<ActionResult> the view doesn't load, it still in base View.

The HTTP response is returned to the caller which is the AJAX success callback handlers.  The success handler is empty.

function Edit(idEmployee) {
    $.ajax({
        url: '@Url.Action("EditEmployee/id","Employees")'.replace('id', idMain),
        type: 'post',
        dataType: 'json',
        contentType: 'application/json;charset=utf-8',
     success: function () {
        },
        error: function (error) {
            alert(error.statusText);
        }
    });
}

It should look similar to 

function Edit(idEmployee) {
    $.ajax({
        url: '@Url.Action("EditEmployee/id","Employees")'.replace('id', idMain),
        type: 'post',
        dataType: 'json',
        contentType: 'application/json;charset=utf-8',
        success: function (response) {
            $('#MyContent').html(response);
        },
        error: function (error) {
            alert(error.statusText);
        }
    });
}

And you'll want to return a partial.  Otherwise you'll have duplicate navigation etc.

 return PartialView("NewEmployeePage",VMemployee ); 

Keep in mind there's questionable code shown which could be causing issues too but the main issue is understanding the XHR response is returned to the code.  The browser does not refresh the page when code makes an HTTP request.


Thursday, March 14, 2019 7:49 PM

Mr.mgebhard

Thanks for fast response, I tried what you mentioned but still not working, still the alert going to alert Error >> " OK "

!! For > 

$('#MyContent').html(response);

I will replace MyContent with what ??

Thursday, March 14, 2019 8:11 PM

I tried what you mentioned but still not working, still the alert going to alert Error >> " OK "

!! For >

Your code has a lot of issues.  Try one of these URLs.

url: '@Url.Action("EditEmployee","Employees")/' + idMain

Or

url: '@Url.Action("EditEmployee","Employees")/' + idEmployee

Or hard code the id with a know Id.  It is not clear where the id is set or what id you're using.

url: '@Url.Action("EditEmployee","Employees")/1'

$('#MyContent').html(response);

I will replace MyContent with what ??

That's something you must decide or maybe design.  I cannot see your View as it is not posted.  Lets assume the View has an outer container like this View below.

@{
    ViewData["Title"] = "AjaxDemo";
}

<h4>AjaxDemo</h4>

<div id="MyContent">
    <!-- View Contents -->
</div>

Thursday, March 14, 2019 8:16 PM

Dear mgebhard,

I tried to write this and it is working now :

 function EditModule(idEmployee) {
alert(idModule);
window.location = '@Url.Action("EditEmployee/id", "Employees")'.replace('id', idEmployee);
}

it is working without ajax !!

I guess that works but I assume you could simply render the URLs with the IDs without using JavaScript.

I recommend the following tutorial.

/en-us/aspnet/mvc/overview/getting-started/introduction/getting-started