Created
January 8, 2014 11:28
-
-
Save eduardosilva/8315474 to your computer and use it in GitHub Desktop.
class to generate standardization in json returns
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; } | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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