如何将LINQ结果转换为JSON并将其传递给MVC3中的View

时间:2014-01-28 15:26:58

标签: asp.net-mvc-3

在我的控制器中,我有以下代码

public ActionResult 
{
    var roomdetails = db.RoomDetails.Include(r => r.RoomType).Include(r => r.FloorNames);

    roomdetails = roomdetails.OrderByDescending(s => s.FloorNames.FloorName);

    return View(roomdetails.ToList());
}

但我想发送roomdetails作为json对象,以便我可以使用jquery来捕获请求并在我的View中进行进一步的动态处理。所以如何将roomdetails转换为json对象。请帮助我......

4 个答案:

答案 0 :(得分:1)

注意:使用Newtonsoft.Json.dll版本8.0.2

将此类的实例返回给控制器方法。

public class ActionResult_Json : System.Web.Mvc.ActionResult
{
    public object To_Serialize_Object { get; set; }
    public ActionResult_Json(object To_Serialize_Object)
    {
        this.To_Serialize_Object = To_Serialize_Object;
    }
    public override void ExecuteResult(ControllerContext context)
    {
        context.HttpContext.Response.ContentType = "application/json";
        //serialize object to string
        string Serialized_Object_String =          Newtonsoft.Json.JsonConvert.SerializeObject(To_Serialize_Object, new Newtonsoft.Json.JsonSerializerSettings()
        {
            ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore,
        });
        //write json to response stream
        context.HttpContext.Response.Write(Serialized_Object_String);
    }
}

答案 1 :(得分:0)

只需返回一个JsonResult:

public JsonResult Index()
{
    var roomdetails = db.RoomDetails.Include(r => r.RoomType).Include(r => r.FloorNames)
                                    .OrderByDescending(s => s.FloorNames.FloorName);
    return Json(roomdetails.ToList(), JsonRequestBehavior.AllowGet); 
}

你需要你的jquery以你想要的方式处理json并显示你想要的东西。通常情况下,如果通过ajax从您的视图中调用它,则效果很好。

答案 2 :(得分:0)

@ {

ViewBag.Title = "Index";

}

接收

    $(document).ready(function(){         $ .getJSON('/ Reception / Index1',function(data){             的console.log(数据);             if(data.success){                 警报( “辞海”);                 // ShowStockQuote(数据);             }             其他{                 警报( “faliure”);             }         });     });

    @ Html.ActionLink(“创建新”,“创建”)

答案 3 :(得分:-1)

你可以试试这个。

public JsonResult Index()
{
    var roomdetails = db.RoomDetails.Include(r => r.RoomType).Include(r => r.FloorNames);
    roomdetails = roomdetails.OrderByDescending(s => s.FloorNames.FloorName);

    return Json(roomdetails.ToArray(), JsonRequestBehavior.AllowGet);
}