0

I am using the jQuery code below to search for an employee and once the employee exists, other fields in the table are returned.

I want to be able to send an alert to the user if the employee was not found. How can I achieve that?

$(document).on("click", "#btnEmpNumber", function () {
    var getdata = $('#EmpNumber').val();
    var url = "@Url.Action("GetEmployeeInformation", "Home")";

    $.post(url, { 'objdata': getdata }, function (data) {
        if (data == undefined) {
            alert("Invalid Employee");
        }

        $('#mainYourinformation').html(data);
    });
});
public ActionResult GetEmployeeInformation(string objdata)
{
    Customerproductdto objGetEmpData = null;
    try
    {
        objGetEmpData = _DataService.SearchEmplByNumber(objdata);
    }
    catch (Exception ex)
    {
        logger.Error(ex);
    }

    return PartialView("_Empinformation", objGetEmpData);
}

public class Customerproductdto
{
    public string EmployeeNumber { get; set; }
    public string EmployeeName { get; set; }
    public string EmployeePhone { get; set; }
    public string EmployeeTitle { get; set; }        
}
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Baba
  • 2,059
  • 8
  • 48
  • 81

2 Answers2

2

Assuming your SearchEmplByNumber return null when the employee was not found, you can return a different result from your action method.

public ActionResult GetEmployeeInformation(string objdata)
{
    Customerproductdto objGetEmpData = null;
    try
    {
        objGetEmpData = _DataService.SearchEmplByNumber(objdata);
    }
    catch (Exception ex)
    {
        logger.Error(ex);
    }
    if(objGetEmpData!=null)
       return PartialView("_Empinformation", objGetEmpData);

    return Content("No information found for the employee");
}

If you want fancy html markup than the simply message, create a new partial view with those fancy markup and return that.

    if(objGetEmpData!=null)
       return PartialView("_Empinformation", objGetEmpData);

    return PartialView("NoDataFoundForEmployee");

Assuming you have a view called NoDataFoundForEmployee.cshtml in ~/Views/Shared or ~/Views/Home/

There is no need of the if condition in your $.post success callback as your action method will always return some response.

EDIT : As per the comment

I am using toastr to return messages and thats what I want to stick to

In this case, you may always return a json response from your action method with the below structure

{ 
  status="found",
  message="some Message for the user",
  resultMarkup="somehtmlToDisplayToUser"
}

You can use the below helper method(took from this answer) to convert your view result to a string

public string RenderRazorViewToString(string viewName, object model)
{
  ViewData.Model = model;
  using (var sw = new StringWriter())
  {
    var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext,
                                                             viewName);
    var viewContext = new ViewContext(ControllerContext, viewResult.View,
                                 ViewData, TempData, sw);
    viewResult.View.Render(viewContext, sw);
    viewResult.ViewEngine.ReleaseView(ControllerContext, viewResult.View);
    return sw.GetStringBuilder().ToString();
  }
}

Now in your action method,

public ActionResult GetEmployeeInformation(string objdata)
{
    Customerproductdto objGetEmpData = null;
    try
    {
        objGetEmpData = _DataService.SearchEmplByNumber(objdata);
    }
    catch (Exception ex)
    {
        logger.Error(ex);
         return Json(new { status="error", message="System Error!" });
    }
    if(objGetEmpData!=null)
    {
        var h= RenderRazorViewToString("_Empinformation", objGetEmpData);
        return Json(new { status="found", resultMarkup = h });
    }
    return Json(new { status="notfound", message="Employee not found" });
}

Now in your $.post method's callback, check the json response's status property value and show the markup or messsage.

$.post(url, { 'objdata': getdata }, function (data) {
    if (data.status==="found") {
        $('#mainYourinformation').html(data.resultMarkup);
    }
    else
    {
       alert(data.message);
       // or call the toastr method here
      // toastr.error(data.message, 'Not found')
    }

});
Community
  • 1
  • 1
Shyju
  • 214,206
  • 104
  • 411
  • 497
  • I am using toastr to return messages and thats what I want to stick to. Thanks – Baba Dec 30 '16 at 15:22
  • I really dont want to create another partial view. I want the main form to still be on the page and alert displays " No information was found" – Baba Dec 30 '16 at 15:25
1

Return the exception from controller and catch that exception in catch block of $.post method and show alert to the user.

   $.post(url, { 'objdata.....).catch (function (ex){ 
         alert (ex);   
     });
Developer
  • 6,240
  • 3
  • 18
  • 24