渲染前向局部视图添加错误
Add errors to the Partial View before rendering
我有一些代码可以根据某些模型将 部分视图 渲染为 html。
然后我将 html 发送到页面。
如果出现错误我想使用
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
为了展示它们。
所以我的问题如下:是否可以在渲染之前向模型添加一些错误?
#region Regenerate Partial View in case of error
var moduleLocation = new ModuleLocation(); // Some custom class
string renderedPartialView = RenderPartialViewToString("_CreateLocationModalPartial", moduleLocation);
#endregion
#region Method to render Partial View
public string RenderPartialViewToString(string viewName, object model)
{
if (string.IsNullOrEmpty(viewName))
viewName = ControllerContext.RouteData.GetRequiredString("action");
ViewData.Model = model;
using (StringWriter sw = new StringWriter())
{
ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
ViewContext viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
viewResult.View.Render(viewContext, sw);
return sw.GetStringBuilder().ToString();
}
}
#endregion
是的,通过将错误添加到 ModelState
:
ViewData.ModelState.AddModelError("key", "error")
我有一些代码可以根据某些模型将 部分视图 渲染为 html。
然后我将 html 发送到页面。
如果出现错误我想使用
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
为了展示它们。
所以我的问题如下:是否可以在渲染之前向模型添加一些错误?
#region Regenerate Partial View in case of error
var moduleLocation = new ModuleLocation(); // Some custom class
string renderedPartialView = RenderPartialViewToString("_CreateLocationModalPartial", moduleLocation);
#endregion
#region Method to render Partial View
public string RenderPartialViewToString(string viewName, object model)
{
if (string.IsNullOrEmpty(viewName))
viewName = ControllerContext.RouteData.GetRequiredString("action");
ViewData.Model = model;
using (StringWriter sw = new StringWriter())
{
ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
ViewContext viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
viewResult.View.Render(viewContext, sw);
return sw.GetStringBuilder().ToString();
}
}
#endregion
是的,通过将错误添加到 ModelState
:
ViewData.ModelState.AddModelError("key", "error")