ExtJS:如何使用asp.net mvc返回json成功w / data

我正在尝试将ExtJS与Asp.Net MVC一起使用,到目前为止一切正常。 (在ExtJS上做得很好)为了简化操作,我需要一些帮助将数据从.net返回到ExtJS。

ExtJS希望在JSON Respone中看到成功标志以及其他数据。

样本预期响应格式是类似的

{success:true,data:{id:3,text:“hello world}}

所以,使用linq2sql或ado.net数据集作为模型对象,您是否知道如何以这种格式轻松返回数据。

就像是

public JsonResult Index() { result.success= true; result.obj = repository.FindAllUsers(); return Json(result) } 

会顺便说一下吗? 如果我有一个具有bool成功和对象数据属性的ExtJSResult类?

提前致谢

试试这个……

 public JsonResult Index() { var json = new { success = true, data = from user in repository.FindAllUsers().AsQueryable() select new { id = user.Id, name = user.Name, ... } }; return Json(json); } 

我正在使用Newtonsoft.Json以及Rick Strahl的一些代码,它们有助于序列化Data对象。 他原来的post: http : //www.west-wind.com/Weblog/posts/471835.aspx

  public class ExtJSJsonResult : JsonResult { public bool success { get; set; } public string msg { get; set; } public override void ExecuteResult(ControllerContext context) { if (context == null){ throw new ArgumentNullException("context");} HttpResponseBase response = context.HttpContext.Response; if (!String.IsNullOrEmpty(ContentType)) { response.ContentType = ContentType; } else { response.ContentType = "application/json"; } if (ContentEncoding != null) { response.ContentEncoding = ContentEncoding; } if (Data != null) { Type type = Data.GetType(); response.Write(String.Format("{{success: true, msg: \"{0}\", data:", msg)); if (type == typeof(DataRow)) response.Write(JSonHelper.Serialize(Data, true)); else if (type == typeof(DataTable)) response.Write(JSonHelper.Serialize(Data, true)); else if (type == typeof(DataSet)) response.Write(JSonHelper.Serialize(Data, true)); else { JavaScriptSerializer serializer = new JavaScriptSerializer(); response.Write(serializer.Serialize(Data)); } response.Write("}"); } } } 

使用它

 public ExtJSJsonResult View(int id) { bool success; string msg; DataRow dr=null; try { dr = DBService.GetRowById("oc.personeller", id); success = true; msg = "all ok"; } catch (Exception ex) { success = false; msg = ex.Message; } return new ExtJSJsonResult { success= success, msg = msg, Data = dr }; } 

我希望这对我以外的人有用。

我使用@ Wellington对VS2010(beta2)和MVC 2(beta)的回答 ,并得到以下错误:

方法’System.String ToString(System.String)’没有支持的SQL转换。

我认为,这是一个序列化问题(?)

这是我改变它使它工作..

 public JsonResult Index() { var json = new { success = true, data = from user in repository.Users select new JsonUser(user) }; return Json(json); } 

JsonUser是一个简单的,可序列化的对象 – 我从@ Scott Hanselman的播客那里得到了这个想法

这是JsonUser的一个例子:

 public class JsonUser { public long id { get; set; } public string name { get; set; } public string dateJoined { get; set; } ... public JsonUser(User user) { id = user.ID; name = user.Name; dateJoined = user.DateJoined.ToString("yyyy-MM-dd"); ... } }