How to get error message or success after call action function using jquery ajax ?

Ahmed Abd El Aziz 315 Reputation points
2023-09-13T09:00:41.16+00:00

I work on asp.net MVC application . I face issue I can't display error message or success message when call action RequesterIndex controller Resignation .

calling API using ajax request working success only need to display error message or success message on sweet alert .

public async Task RequesterIndex(ResignationRequester resignationRequester) {
  var filenumber = resignationRequester.EmpID;
  if (Session[SessionKeys.UserCode] != null) {
    if (ModelState.IsValid) {
      if (resignationRequester.DirectManager == 0) {
        resignationRequester.errorMsg = "Department Manager Must Be Bigger Than 0";
        goto InvalidModel;
      }
      if (Convert.ToString(resignationRequester.LineManager).Length < 6 && !string.IsNullOrEmpty(resignationRequester.LineManager.ToString())) {
        resignationRequester.errorMsg = "Length Line Manager Must Be equal 6 or More";
        goto InvalidModel;
      }
      if (Convert.ToString(resignationRequester.DirectManager).Length < 6 && !string.IsNullOrEmpty(resignationRequester.DirectManager.ToString())) {
        resignationRequester.errorMsg = "Length Direct Manager Must Be equal 6 or More";
        goto InvalidModel;
      }
      if (!string.IsNullOrEmpty(Convert.ToString(resignationRequester.LineManager)) && resignationRequester.LineManagerName == null) {
        resignationRequester.errorMsg = "Line Manager Name Blank";
        goto InvalidModel;
      }
      if (julianRequestDate > 0 && SubmitionDate > 0 && julianRequestDate < SubmitionDate) {
        resignationRequester.errorMsg = "Last Worked Date Must be Bigger than Submit Date";
        goto InvalidModel;
      }

      int checkEmployeeNoExist = jde.CheckEmployeeExistOrNot(resignationRequester.EmpID);
      if (checkEmployeeNoExist >= 1) {
        resignationRequester.errorMsg = "Employee Exist Before";
        goto InvalidModel;
      }
     try {
        Workforce.InsertToReignation(resignationRequester, (string) Session[SessionKeys.Username], (DateTime) Session[SessionKeys.LastWorkingDate], noticeperiod, (int) Session[SessionKeys.UserCode]);
      } catch (Exception ex) {
        resignationRequester.errorMsg = "Create Not Done Correctly";
      }

      if (string.IsNullOrEmpty(ViewBag.errorMsg)) {
        resignationRequester.successMsg = "Resignation Submission form Created successfully";
      }
    } else {
      var errors = ModelState.Select(x => x.Value.Errors)
        .Where(y => y.Count > 0)
        .ToList();
      resignationRequester.errorMsg = "Some Required Fields Not Added";
      goto InvalidModel;
    }
  } else {
    resignationRequester.errorMsg = "No Data For This File No";
  }
  InvalidModel:
    ViewBag.isPostBack = true;
}

Expected result

display message of resignationRequester.errorMsg ON API AJAX Call if it exist

OR

display message of resignationRequester.successMsg ON API AJAX Call if it exist

meaning display result of action RequesterIndex calling on sweet alert

$('#btnsubmit').click(function() {
  $("#ResignationApp").submit(function(e) {
    e.preventDefault(); // Prevent the default form submission
    // Serialize the form data
    var formData = $(this).serialize();
    console.log("data is" + formData)
    $.ajax({
      type: "POST",
      url: '@Url.Action("RequesterIndex", "Resignation")',
      data: formData,
      success: function(response) {
        var errorMsg = '@Html.Raw(Json.Encode(ViewData["ErrorMessage"]))';
        Swal.fire({
          icon: 'error',
          title: 'Submition Request',
          text: errorMsg
        });
      },
      error: function(error) {
        // Handle any errors here
        console.error(error);
      }
    });
  });
});
Developer technologies ASP.NET Other
{count} votes

Accepted answer
  1. Lan Huang-MSFT 30,186 Reputation points Microsoft External Staff
    2023-09-14T06:23:14.47+00:00

    Hi @Ahmed Abd El Aziz,

    In your action method, return Json(object) to return JSON to your page.

    if (string.IsNullOrEmpty(resignationRequester.errorMsg))
    {
        resignationRequester.successMsg = "Resignation Submission form Created successfully";
        return Json(new { success = true, responseText = resignationRequester.successMsg }, JsonRequestBehavior.AllowGet);
    }
    else
    {
        return Json(new { success = false, responseText = resignationRequester.errorMsg }, JsonRequestBehavior.AllowGet);
    }
    

    Then get the responseText from the response in success.

     success: function (response) {
    
         if (response.success) {
             Swal.fire({
                 icon: 'success',
                 title: 'Submition Request',
                 text: response.responseText
             });
         } else {
             Swal.fire({
                 icon: 'error',
                 title: 'Submition Request',
                 text: response.responseText
             });
         }
    
     },
    

    Below is an example of my test, you can refer to it.

     public class ResignationController : Controller
     {
         // GET: Resignation
         public ActionResult RequesterIndex(string filenumber)
         {
             ResignationRequester resignationRequester = new ResignationRequester();
             return View(resignationRequester);
         }
         [HttpPost]
         public ActionResult RequesterIndex(FormCollection formCollection)
         {
             ResignationRequester resignationRequester = new ResignationRequester();
             resignationRequester.DirectManager = Convert.ToInt32(formCollection["DirectManager"]);
             resignationRequester.LineManager = formCollection["LineManager"];
             if (ModelState.IsValid)
             {
    
                 if (resignationRequester.DirectManager == 0)
                 {
                     resignationRequester.errorMsg = "Department Manager Must Be Bigger Than 0";
                     goto InvalidModel;
                 }
                 if (Convert.ToString(resignationRequester.LineManager).Length < 6 && !string.IsNullOrEmpty(resignationRequester.LineManager.ToString()))
    
                 {
                     resignationRequester.errorMsg = "Length Line Manager Must Be equal 6 or More";
                     goto InvalidModel;
                 }
                 if (Convert.ToString(resignationRequester.DirectManager).Length < 6 && !string.IsNullOrEmpty(resignationRequester.DirectManager.ToString()))
                 {
                     resignationRequester.errorMsg = "Length Direct Manager Must Be equal 6 or More";
                     goto InvalidModel;
                 }
             }
             else
             {
                 var errors = ModelState.Select(x => x.Value.Errors)
                   .Where(y => y.Count > 0)
                   .ToList();
                 resignationRequester.errorMsg = "Some Required Fields Not Added";
                 goto InvalidModel;
             }
         InvalidModel:
             ViewBag.isPostBack = true;
             if (string.IsNullOrEmpty(resignationRequester.errorMsg))
             {
                 resignationRequester.successMsg = "Resignation Submission form Created successfully";
                 return Json(new { success = true, responseText = resignationRequester.successMsg }, JsonRequestBehavior.AllowGet);
             }
             else
             {
                 return Json(new { success = false, responseText = resignationRequester.errorMsg }, JsonRequestBehavior.AllowGet);
             }
         }
     }
    
    @{
        ViewBag.Title = "Requester Index";
    }
    
    @using (Html.BeginForm("RequesterIndex", "Resignation", FormMethod.Post, new { enctype = "multipart/form-data", @id = "ResignationApp", style = "padding-top: 50px" }))
    {
    
        <div class="form-horizontal">
    
            <div class="row">
                <div class="form-group col-md-6 hover">
                    <div class="col-md-5">
                        @Html.LabelFor(model => model.DirectManager, htmlAttributes: new { @class = "control-label" })
                    </div>
    
                    <div class="col-md-7">
                        @Html.EditorFor(model => model.DirectManager, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.DirectManager, "", new { @class = "text-danger" })
                    </div>
                </div>
                <div class="form-group col-md-6 hover">
                    <div class="col-md-5">
                        @Html.LabelFor(model => model.LineManager, htmlAttributes: new { @class = "control-label" })
                    </div>
    
                    <div class="col-md-7">
                        @Html.EditorFor(model => model.LineManager, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.LineManager, "", new { @class = "text-danger" })
                    </div>
                </div>
            </div>
    
    
            <div class="form-group">
                <div class="col-md-offset-0 col-md-12">
                    <input type="submit" value="Submit" class="btn btn-success" />
                </div>
            </div>
        </div>
    }
    
    @section Scripts {
        @Scripts.Render("~/bundles/jqueryval")
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11.0.16/dist/sweetalert2.all.min.js"></script>
    <script>
    
        $("#ResignationApp").submit(function (e) {
            e.preventDefault(); // Prevent the default form submission
    
            var formData = $(this).serialize();
            console.log("data is" + formData)
            $.ajax({
                type: "POST",
                url: '@Url.Action("RequesterIndex", "Resignation")',
                data: formData,
    
                success: function (response) {
    
                    if (response.success) {
                        Swal.fire({
                            icon: 'success',
                            title: 'Submition Request',
                            text: response.responseText
                        });
                    } else {
                        Swal.fire({
                            icon: 'error',
                            title: 'Submition Request',
                            text: response.responseText
                        });
                    }
    
                },
                error: function (error) {
                    console.error(error);
                }
            });
    
        });
    </script>
    
    
    
     public class ResignationRequester
     {
         [Required]
         public int DirectManager { get;  set; }
         [Required]
         public string LineManager { get;  set; }
         public string errorMsg { get;  set; }
         public string successMsg { get;  set; }
     }
    

    11

    Best regards,
    Lan Huang


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 77,686 Reputation points Volunteer Moderator
    2023-09-13T17:52:34.4966667+00:00

    your api call doesn't return any data. you should change to return some response. The code appears to update the passed model, but this does not send any information back to the ajax caller. also the api update the ViewBag, but a viewbag values is only used if the action return a view.

    in the sample ajax:

          var errorMsg = '@Html.Raw(Json.Encode(ViewData["ErrorMessage"]))';
      
    

    the errorMsg is set to the ViewData value at page render (do a view source of the page). an ajax call will not change the value.

    as you only want success/fail, what is wrong with using the response codes 200 / 500 status message?

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.