views:

2139

answers:

3

Hello, I am trying to use ExtJS with Asp.Net MVC, and it is going fine so far. (Nice work on ExtJS) To make things easier, I need some help returning data from .net to ExtJS.

ExtJS expects to see a success flag in the JSON Respone along with additional data.

a sample expectedresponse format is something like

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

so, using either linq2sql or ado.net dataset for model objects, do you guys have any idea how to easily return data in this format.

Something like

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

would that work by the way? if I had a ExtJSResult class with bool success and Object data properties?

thanks in advance

+3  A: 

Try this one...

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);
}
Wellington
looks really nice. Linq scares me to death, and I was using DataSets in this situation. so I came up with a different solution which should work with good old DataSets. I guess I'll have to learn and start using Linq one day. (so far I just could not aggree on what O/RM to use so I am using a little Linq2Sql and some classic Ado.Net.
hazimdikenli
A: 

I was using Newtonsoft.Json along with some code from Rick Strahl, which helps serialize Data objects. his original post here: 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("}");
            }
        }
    }

using it

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
    };

}

I hope this is of any use to someone besides me.

hazimdikenli
A: 

I used @Wellington's answer with VS2010 (beta2) and MVC 2 (beta), and got the following error:

Method 'System.String ToString(System.String)' has no supported translation to SQL.

Which, I think, is a serialization problem (?)

Here's what I changed to make it work..

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

JsonUser is a simple, serializable object - I got the idea from a podcast by @Scott Hanselman

Here's an example of 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");
        ...
    }
}
Andrew