1
在asp.net核心1.0(Full Framework 4.6.1)中,我需要渲染一個局部視圖到字符串,所以基於https://gist.github.com/ahmad-moussawi/1643d703c11699a6a4046e57247b4d09,我創建的RenderView:當在asp.net核心1.0中渲染部分視圖時,ViewBag數據不存在
public class ViewRender
{
private IRazorViewEngine _viewEngine;
private ITempDataProvider _tempDataProvider;
private IServiceProvider _serviceProvider;
public ViewRender(
IRazorViewEngine viewEngine,
ITempDataProvider tempDataProvider,
IServiceProvider serviceProvider)
{
_viewEngine = viewEngine;
_tempDataProvider = tempDataProvider;
_serviceProvider = serviceProvider;
}
public string Render<TModel>(string view, TModel model)
{
var actionContext = GetActionContext();
var viewEngineResult = _viewEngine.FindView(actionContext, view, false);
if (!viewEngineResult.Success)
{
throw new InvalidOperationException(string.Format("Couldn't find view '{0}'", view));
}
var viewResult = viewEngineResult.View;
using (var output = new StringWriter())
{
var viewContext = new ViewContext(
actionContext,
viewResult,
new ViewDataDictionary<TModel>(
metadataProvider: new EmptyModelMetadataProvider(),
modelState: new ModelStateDictionary())
{
Model = model
},
new TempDataDictionary(
actionContext.HttpContext,
_tempDataProvider),
output,
new HtmlHelperOptions());
viewContext.Vi
viewResult.RenderAsync(viewContext).GetAwaiter().GetResult();
return output.ToString();
}
}
private ActionContext GetActionContext()
{
var httpContext = new DefaultHttpContext();
httpContext.RequestServices = _serviceProvider;
return new ActionContext(httpContext, new RouteData(), new ActionDescriptor());
}
}
然而,當控制器調用PartialView:
string render = _viewRender.Render("Directory/_DirectoryData", directory);
數據集分成ViewBag控制器先前如下。
<label asp-for="DirectoryItem_DirectoryItem" class="form-control-label"></label>
<select asp-for="DirectoryItem_DirectoryItem" asp-items="@(new SelectList(ViewBag.DirectoryList, "Id", "DirectoryId", null))" class="form-control">
<option>--- Seleccione ---</option>
</select>
和渲染拋出異常:當使用它們的組合框項目
ViewBag.ParticipantTypesList = _dbInstance.ParticipantTypes;
ViewBag.DirectoryList = _dbInstance.Directories;
ViewBag.TaxCategoryList = _dbInstance.TaxCategories;
不存在。請幫助我如何獲取或傳輸ViewBag。
¿我必須使用_viewEngine.FindView(...)或_viewEngine.FindPage(...)?
謝謝