ajax模块处理--仿新浪微博开源剖析2
由于微博是一个前端与后端交互相应频繁的系统,所以,ajax的开发也要相应有规范
*本系统是asp.net mvc开发的
首先建俩个model,(其中一个用于分页的)
public class JsonModel { public string Code { get; set; } public object Data { get; set; } public JsonModel(string code, object data) { Code = code; Data=data; } } public class PagerJsonModel : JsonModel { public int Count { get; set; } public PagerJsonModel(string code, object data,int count):base(code,data) { Count = count; } }
Code为处理结果代码,是一个枚举值,Data表示要传输的实际数据
public struct CodeStruct { //已经登录 public static string HaveLogon = "A00000"; public static string NoLogin = "A00001"; public static string NoUserExist = "A00002"; public static string Error = "A00003"; 。。。。
然后在control里面这样写,例如
public JsonResult JudgeLogin() { if (!IsLogin) return NotLogin(); else return Json(new JsonModel(CodeStruct.HaveLogon, new { name = CurrentUser.NickName, id = CurrentUser.ID })); }
调用的话会返回数据,例如
{"Code":"A00000","Data":{"name":"天才程序员","id":6}}
前端调用
$(function () { $.ajax({ url: "/Ajax/JudgeLogin", datatype: "json", cache: false, type: "post", success: function (o) { if (o.Code == "A00000") { //todo alert(CodeList[o.Code]);
} else{ //todo } });
同时前端也有相应的枚举数据,例如:
var CodeList = { A00000: "已登录", A00001:"还没有登录", A00002:"用户不存在", A00003:"出错,请稍后再试", ....
那么假如要返回一些数据是html代码,来自于由某个view和model渲染出来的代码,我使用了以下的代码来转换
/// <summary> /// 渲染cshtml页面成字符串 /// </summary> /// <param name="viewName">页面名</param> /// <param name="model">模型</param> /// <returns></returns> public string RenderRazorViewToString(string viewName, object model) { ViewData.Model = model; using (var sw = new StringWriter()) { var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName); var viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw); viewResult.View.Render(viewContext, sw); return sw.GetStringBuilder().ToString(); } }
然后调用
string data = RenderRazorViewToString("GetCommentsHtml", model); if (!string.IsNullOrEmpty(data)) { return Json(new JsonModel(CodeStruct.ReturnSuccess, data)); }
这样返回的html数据可以填充到一个容器里面去显示。
打完继续搵工
源码发布页http://www.cnblogs.com/baichidetiankong/archive/2012/04/17/weibo_source.html