在我的控制器中,我有以下代码
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对象。请帮助我......
答案 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";
}
@ 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);
}