在渲染前向局部视图添加错误

本文关键字:视图 添加 错误 局部 | 更新日期: 2023-09-27 18:11:59

我有一些代码渲染部分视图基于一些模型到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")