What is the best way to return File or ErrorMessage from Asp.net-mvc controller action?
I would initiate a $.get request to another controller action that would check for the order count. Return that value, along with an error message if appropriate. Display the error message when it's needed, otherwise process your redirect to download your file. It's an extra call to the controller but it allows you to have full control and handle the possibility of an error without redirecting your user.
$("#exportPPT").live('click', function (e) {
$.get( "/Initiative/CheckForOrders" + GenerateParams(), function( data ) {
if (data.IsValid) {
window.location.href = "/Initiative/GenerateFile" + GenerateParams();
} else {
alert(data.ErrorMessage); // or show a div containing error message
}
});
});
Controller Action:
public ActionResult CheckForOrders(MyParams myParams)
{
IEnumerable<Order> orders = Model.GetOrders(myparams);
if (orders.Any())
return Json(new { IsValid=true }, JsonRequestBehavior.AllowGet);
return Json(new { IsValid=false, ErrorMessage="No orders" }, JsonRequestBehavior.AllowGet);
}
I'd return a status that represents that a resource doesn't exist and return null? Then you can handle it accordingly in you javascript without worrying about doing multiple ajax calls to check one is available or the security implications if somebody bypasses such checks.
For example...
Controller
public ActionResult GenerateFile(MyParams myParams)
{
var template = Server.MapPath(PPT_ROOT + "/template.pptx");
IEnumerable<Order> orders = Model.GetOrders(myparams);
if(!orders.Any()){
Response.StatusCode = (int)HttpStatusCode.NotFound
Response.StatusDescription = HttpStatusCode.NotFound.ToString();
Response.TrySkipIisCustomErrors = true;
return EmptyResult;
}
var pptResults = GeneratePowerpointFile(orders);
return new File(pptResults.Content, "application/vnd.ms-powerpoint", pptResults.FileName);
}