Skip to content

Instantly share code, notes, and snippets.

@eduardosilva
Created January 8, 2014 11:28
Show Gist options
  • Save eduardosilva/8315474 to your computer and use it in GitHub Desktop.
Save eduardosilva/8315474 to your computer and use it in GitHub Desktop.
class to generate standardization in json returns
public interface ICustomJsonResult
{
bool Success { get; set; }
string Message { get; set; }
CustomJsonResult Succeed();
CustomJsonResult Succeed(string message);
CustomJsonResult Fail();
CustomJsonResult Fail(string message);
}
public interface ICustomJsonResult<T> : ICustomJsonResult
{
T Value { get; set; }
}
public class CustomJsonResult : ICustomJsonResult
{
public bool Success { get; set; }
public string Message { get; set; }
public CustomJsonResult Succeed()
{
return Succeed(message: null);
}
public CustomJsonResult Succeed(string message)
{
Success = true;
Message = message;
return this;
}
public CustomJsonResult Fail()
{
return Fail(message: null);
}
public CustomJsonResult Fail(string message)
{
Success = false;
Message = message;
return this;
}
}
public class CustomJsonResult<T> : CustomJsonResult, ICustomJsonResult<T>
{
public CustomJsonResult() { }
public CustomJsonResult(T value)
{
Value = value;
}
public T Value { get; set; }
}
public JsonResult ExampleA()
{
try
{
//my code
return Json(new CustomJsonResult().Succeed(), JsonRequestBehavior.AllowGet);
}
catch(ex)
{
return Json(new CustomJsonResult().Fail(), JsonRequestBehavior.AllowGet);
}
}
public JsonResult ExampleB(decimal price)
{
try
{
var result = Dispatcher.ExecuteCommand<CreateQuotationCommand,
CreateQuotationCommandResult>(new CreateQuotationCommand{
Price = price
});
return Json(new CustomJsonResult<CreateQuotationCommandResult>(result).Succeed(), JsonRequestBehavior.AllowGet);
}
catch(ex)
{
return Json(new CustomJsonResult().Fail(""), JsonRequestBehavior.AllowGet);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment