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')
}
});