我正在编写一个 ASP.NET Core 6 MVC 应用程序。
我在控制器中有一个方法需要像这样检索 Json 值
一个布尔值和一个带有模型类的局部视图
return Json(new { success = true, PartialView("SearchResult", resultViewModel) });
我发现这篇文章说要将 PartialView 检索为字符串。 [这里][1]
像这样
return Json(new { error = true, message = RenderViewToString(PartialView("Evil", model))});
我没有
RenderViewToString
功能。搜索..我找到了这个
protected string RenderViewAsString( string viewName, object model)
{
viewName = viewName ?? ControllerContext.ActionDescriptor.ActionName;
ViewData.Model = model;
using (StringWriter sw = new StringWriter())
{
IView view = _viewEngine.FindView(ControllerContext, viewName, true).View;
if(view!=null)
{
ViewContext viewContext = new ViewContext(ControllerContext, view, ViewData, TempData, sw, new HtmlHelperOptions());
view.RenderAsync(viewContext).Wait();
}
return sw.GetStringBuilder().ToString();
}
}
问题是它返回一个
View
而不是一个PartialView
有没有办法让它返回 PartialView?
谢谢 [1]: MVC 以 JSON 形式返回部分视图
问题是它返回一个 View 而不是 PartialView
尝试在您的 PartialView 中添加以下内容:
@{
Layout = null;
}
我的演示如下:
[HttpPost]
public IActionResult Details(string customerId)
{
Phone phone = GetCustomers().Where(x => x.Id == Convert.ToInt32(customerId)).FirstOrDefault().Phone;
PartialViewResult partialViewResult = PartialView("_Phone", phone);
string viewContent = RenderViewToString("_Phone", phone);
return Json(new { PartialView = viewContent });
}
ajax 成功函数:
success: function (response) {
$('#dialog').append('<p>' + response.partialView + '</p>');
}