A wrapper class to return Json result back to the client.
public class JsonResultWrapper
{
public static JsonResultWrapper Create(bool success, string message)
{
return new JsonResultWrapper(success, message);
}
public static JsonResultWrapper Create(bool success, T data) where T : class
{
return new JsonResultWrapperImpl(success, string.Empty, data);
}
public static JsonResultWrapper Create(bool success, string message, T data) where T : class
{
return new JsonResultWrapperImpl(success, message, data);
}
protected JsonResultWrapper(bool success, string message)
{
this.Success = success;
this.Message = message;
}
public bool Success { get; private set; }
public string Message { get; private set; }
}
public class JsonResultWrapperImpl : JsonResultWrapper where T : class
{
public JsonResultWrapperImpl(bool success, string message, T data)
: base(success, message)
{
this.Data = data;
}
public T Data { get; private set; }
}
//How to use this wrapper class.
public class SampleController : Controller
{
public JsonResult Save(Employee emp)
{
//Call the Model class to persist the information.
var id = _employeeService.Save(emp);
var status = id > 0;
new Json(JsonResultWrapper.Create(status, "Employee information saved successfully", new SaveResult()
{Id = id, IsValid = true};
}
}
Client code
No comments:
Post a Comment