Thursday, October 13, 2016

Return View() statement not redirecting to View in ASP.NET MVC using $.ajax() post.

Hello,
Normally, you submit client-side data to a controller action via @Html.BeginForm(), then perform processing statements and lastly invoke the return View(); statement inside the controller action which will redirect you to the view which basically works.

However, in a scenario where-in you will post data to a controller action using jQuery Control Event such as Button Click, the return View() statement in the controller action won't redirect to the specified view given the sample controller action below.
[HttpPost]
public ActionResult UpdatedEmpTrainings(string empId)
{
 _context = new EmployeeEntities();
 model = new List<EmployeeTrainingsViewModel>();
 model = (from emp_trainings in _context.EmployeeTrainings.AsEnumerable()
    join training in _context.Trainings.AsEnumerable()
     on emp_trainings.TrainingID equals training.TrainingID
    where emp_trainings.EmployeeID == Convert.ToInt32(empId)
    select new EmployeeTrainingsViewModel
    {
     TrainingID = emp_trainings.TrainingID.GetValueOrDefault(),
     TrainingTitle = training.TrainingTitle,
     EmployeeID = emp_trainings.EmployeeID.GetValueOrDefault()
    }).OrderBy(t => t.TrainingID).ToList();

 return View(model);
}
So, to resolve the issue in order for the return View() statement to redirect to the said view. In your jQuery $.ajax() success property, set the window.location.href value with the url data returned from the action method.
 $("#tblEmployee").on("click", "#save", function () {
 if (ids.length > 0) {
  $.ajax({
   type: "POST",
   dataType: "json",
   traditional: true,
   data: { courseID: ids, empId: JSON.stringify($('#empTextBox').val()) },
   url: "/Employee/DeleteEmpTrainings",
   success: function (dataUrl) {
    window.location.href = dataUrl;
   }
  });
 }
});
In your action result method, pass the url of the controller action with the return View() statement. Make sure to include the necessary query strings that matches the parameter list of the controller action. This action method below will call the UpdatedEmpTrainings controller action above.
public JsonResult DeleteEmpTrainings(List<string> courseID, string empId)
{
 _context = new EmployeeEntities();
 if(courseID != null)
 {
  foreach (var item in courseID)
  {
   EmployeeTraining emp_training = _context.EmployeeTrainings.AsEnumerable()
    .FirstOrDefault(t => t.TrainingID.GetValueOrDefault() == Convert.ToInt32(item) && t.EmployeeID == Convert.ToInt32(empId));
   _context.EmployeeTrainings.Remove(emp_training);
  }

  _context.SaveChanges();                
 }
 
 return Json(Url.Action("UpdatedEmpTrainings", "Employee", new { empId = empId }), JsonRequestBehavior.AllowGet); 
}
 

0 comments:

Post a Comment