如何从分部视图生成一个 HTML 页面
本文关键字:一个 页面 HTML 视图 | 更新日期: 2023-09-27 18:35:25
假设我有以下类:
class Restaraunt
{
int RestarauntType {get; set;}
string Address {get; set;}
string phone {get; set;}
.....30 more properties
}
所以,我有一个餐厅列表,我有空白的html表单,其中有html元素。
<span class="address"></span>
<span class="email"></span>
现在,我有~5种不同的html布局,它们的大小都相同。
根据餐厅的类型,我想选择一个模板并填写信息,然后选择下一个餐厅并附加它。所以我有很长的 html 页面准备打印。这是我正在考虑的一些伪代码。此外,欢迎有关如何最好地做到这一点的建议。
if (restarauntType==1)
{
var completedForm = GetAndPopulateCsHtmlForm1("/forms/myformNum1.cshtml")
AppendForm(completedForm)
}
else if (restarauntType==2)
{
....
}
在你的主html中,试试这个:
@model System.Collections.Generic.List<Restaurant>
@{
foreach (var restaurant in Model) {
Html.RenderAction("Child", "Restaurants", restaurant);
}
}
在您的RestaurantsController
:
[ChildActionOnly]//optional depending on whether you want to allow rendering this action directly
public ActionResult Child(Restaurant restaurant)
{
string viewName = //GetYourView depending on your restaurant type
return PartialView(viewName, restaurant);
}
有很多方法可以获取您的视图,具体取决于您确定部分的方式。您可以将部分存储在按类型索引的字典中,并像这样访问它以避免切换大小写:
string viewName = restaurantPartial[restaurant.RestarauntType];
然后,您可以有不同的布局,例如:
餐厅1.cshtml
@model Restaurant
<span class="address">@Model.Address</span>
<span class="email">@Model.Email</span>
餐厅2.cshtml:
@model Restaurant
<li class="address">@Model.Address</li>
<li class="email">@Model.Email</li>
我也在做类似的事情。我的 HTML 报告代码的核心是此方法,它允许我将视图呈现为字符串:
public static string RenderRazorViewToString(string viewName, object model)
{
HttpContext context = GetContext();
HttpContextWrapper httpContext = new HttpContextWrapper(context);
RouteData routeData = new RouteData();
routeData.Values.Add("controller", "HtmlFake");
RequestContext requestContext = new RequestContext(httpContext, routeData);
ControllerContext controllerContext = new ControllerContext(requestContext, new HtmlFakeController());
using (var sw = new StringWriter())
{
ViewDataDictionary viewData = new ViewDataDictionary(model);
ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(controllerContext, viewName);
TempDataDictionary tempData = new TempDataDictionary();
ViewContext viewContext = new ViewContext(controllerContext, viewResult.View, viewData, tempData, sw);
viewResult.View.Render(viewContext, sw);
viewResult.ViewEngine.ReleaseView(controllerContext, viewResult.View);
return sw.GetStringBuilder().ToString();
}
}
public class HtmlFakeController : Controller
{
}
对于每个任务,我可以执行:
object model = GetTaskModel(task.Id);
string viewData = RenderRazorViewToString(string.Format("~/Views/Task/{0}.cshtml", taskName), model);
最后,我只是使用 StringBuilder 来联接视图:
sb.Append(viewData);