啊,开始以为MVC+Coolite结合的例子没什么难度,但原来Coolite在MVC中需要特定设置一下某些属性才行,费了两个小时才算大功告成,具体请看下文。还是先把这个例子的效果贴上来再说。
因为默认的 MVC 的样式文件里对于的 table 和 其他相关样式(h1~h6) 与Coolite有冲突,会导致GridPanel走样,大家记得先把那个table 和 h1~h6的样式清除掉才看到GridPanel的帅脸面 …
项目文件分布:
关于Coolite在MVC中的配置文件跟一般webform是一样的。 但在MVC的Global.asax中,需要在 RegisterRoutes 方法里加上这一句:
routes.IgnoreRoute("{exclude}/{coolite}/coolite.axd");
另外 ScriptManager 要注明 IDMode="Static“:
<ext:ScriptManager runat="server" IDMode="Static"/>
其中唯一与一般MVC不同的是,我们需要定义自己的ActionResult来返回Json结果给客户端。因为Coolite 的JsonReader 要求的格式大致都是这样:{data: [{…}], totalCount: …}
关于JsonReader的一般用法:
<ext:JsonReader ReaderID="CustomerID" Root="data" TotalProperty="totalCount">
所以, 要继承MVC ActionResult 的抽象方法 public override void ExecuteResult(ControllerContext context) 来返回给 JsonReader 合适口味的 JsonResult , 不然它就不认人了。
以下代码实现了对Json Response & Save Response 的简单封装。
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using Coolite.Ext.Web; namespace CooliteMVC.Helper { public class AjaxStoreResult : ActionResult { public AjaxStoreResult() { } public AjaxStoreResult(object data) { this.Data = data; } public AjaxStoreResult(object data, int totalCount) : this(data) { this.TotalCount = totalCount; } public AjaxStoreResult(StoreResponseFormat responseFormat) { this.ResponseFormat = responseFormat; } private object data; public object Data { get { return this.data; } set { this.data = value; } } private int totalCount; public int TotalCount { get { return this.totalCount; } set { this.totalCount = value; } } private StoreResponseFormat responseFormat = StoreResponseFormat.Load; public StoreResponseFormat ResponseFormat { get { return this.responseFormat; } set { this.responseFormat = value; } } private SaveStoreResponse saveResponse; public SaveStoreResponse SaveResponse { get { if (this.saveResponse == null) { this.saveResponse = new SaveStoreResponse(); } return this.saveResponse; } } public override void ExecuteResult(ControllerContext context) { switch (this.ResponseFormat) { case StoreResponseFormat.Load: string json = Coolite.Ext.Web.JSON.Serialize(Data); json = "{data:" + json + ", totalCount:" + 100 + "}"; context.HttpContext.Response.Write(json); break; case StoreResponseFormat.Save: Response response = new Response(true); response.Success = this.SaveResponse.Success; response.Msg = this.SaveResponse.ErrorMessage; StoreResponseData saveResponse = new StoreResponseData(); saveResponse.Confirmation = this.SaveResponse.ConfirmationList; response.Data = saveResponse.ToString(); response.Write(); break; default: throw new ArgumentOutOfRangeException(); } } } public enum StoreResponseFormat { Load, Save } public class SaveStoreResponse { private bool success = true; private string errorMessage; public bool Success { get { return this.success; } set { this.success = value; } } public string ErrorMessage { get { return this.errorMessage; } set { this.errorMessage = value; } } public ConfirmationList ConfirmationList { get; set; } } }