有没有办法用JSON结果返回View(“controller”,model)?我这样做了(见下面的代码),但它给我一个错误。
if (thereserror == true)
{
return Json(new
{
view = RenderRazorViewToString(ControllerContext, "Index", model),
isValid = false,
description = "Error!",
JsonRequestBehavior.AllowGet
});
}
else
{
return Json(new
{
view = RenderRazorViewToString(ControllerContext, "Index", model),
isValid = true,
description = "Hey!",
JsonRequestBehavior.AllowGet
});
}
private static string RenderRazorViewToString(ControllerContext controllerContext, string viewName, object model)
{
controllerContext.Controller.ViewData.Model = model;
using (var sw = new StringWriter())
{
var ViewResult = ViewEngines.Engines.FindPartialView(controllerContext, viewName);
var ViewContext = new ViewContext(controllerContext, ViewResult.View, controllerContext.Controller.ViewData, controllerContext.Controller.TempData, sw);
ViewResult.View.Render(ViewContext, sw);
ViewResult.ViewEngine.ReleaseView(controllerContext, ViewResult.View);
return sw.GetStringBuilder().ToString();
}
}
对于我的AJAX,我这样做:
$.ajax({
type: "GET",
url: "/serviceentry/getservice",
data: ({ "SONumber": soNumber }),
success: function (data) {
if (data.isValid) {
//I don't know what to put here
};
},
error: function () {
alert('error');
}
});
我看到类似的东西,但我不知道该怎么做:MVC Return Partial View as JSON
答案 0 :(得分:0)
JSON
包含4个属性,即您访问isValid
的方式,同样可以访问View
。
$.ajax({
type: "GET",
url: "/serviceentry/getservice",
data: ({ "SONumber": soNumber }),
success: function (data) {
if (data.isValid) {
//Element- Where you want to show the partialView
$(Element).html(data.view)
};
},
error: function () {
alert('error');
}
});
PS:同时指出JSONRequestBehavior
的错误位置。
if (thereserror == true)
{
return Json(new
{
view = RenderRazorViewToString(ControllerContext, "Index", model),
isValid = false,
description = "Error!"
},JsonRequestBehavior.AllowGet);
}
else
{
return Json(new
{
view = RenderRazorViewToString(ControllerContext, "Index", model),
isValid = true,
description = "Hey!"
},JsonRequestBehavior.AllowGet);
}
private static string RenderRazorViewToString(ControllerContext controllerContext, string viewName, object model)
{
controllerContext.Controller.ViewData.Model = model;
using (var sw = new StringWriter())
{
var ViewResult = ViewEngines.Engines.FindPartialView(controllerContext, viewName);
var ViewContext = new ViewContext(controllerContext, ViewResult.View, controllerContext.Controller.ViewData, controllerContext.Controller.TempData, sw);
ViewResult.View.Render(ViewContext, sw);
ViewResult.ViewEngine.ReleaseView(controllerContext, ViewResult.View);
return sw.GetStringBuilder().ToString();
}
}