如标题所述。我有一个 MVC 3 Razor 视图,我想以编程方式实例化并获取它的 Html 助手列表。
有人对如何解决这个问题有什么好的建议吗?
提前致谢
如标题所述。我有一个 MVC 3 Razor 视图,我想以编程方式实例化并获取它的 Html 助手列表。
有人对如何解决这个问题有什么好的建议吗?
提前致谢
我可以通过执行自定义视图结果并从我的 html 帮助程序更新模型来实现这一点。
行动方法:
public ActionResult GetListViewHelpers()
{
var model = new TestModel(); // has >>> public List<MyHelper> Helpers { get; set; }
var testContext = new ControllerContext();
testContext.Controller = new MyController();
testContext.HttpContext = HttpContext;
testContext.RouteData.Values["controller"] = "MyController";
testContext.RouteData.Values["action"] = "Index";
var view = new TestViewResult();
view.ViewData.Model = model;
view.ViewName = "TestView"; // i want a list of the helpers from this view
view.ExecuteResult(testContext);
return View(model); // model.Helpers contains a list of helpers within a required view
}
查看结果:
public class TestViewResult : ViewResult
{
public override void ExecuteResult(ControllerContext context)
{
if (context == null)
throw new ArgumentNullException("context");
if (String.IsNullOrEmpty(ViewName))
ViewName = context.RouteData.GetRequiredString("action");
ViewEngineResult result = null;
if (View == null)
{
result = FindView(context);
View = result.View;
}
var stream = new MemoryStream();
var writer = new StreamWriter(stream);
ViewContext viewContext = new ViewContext(context, View, ViewData, TempData, writer);
using (stream)
using (writer)
{
View.Render(viewContext, writer);
writer.Flush();
}
if (result != null)
result.ViewEngine.ReleaseView(context, View);
}
}
帮手:
public static MvcHtmlString AHelper(this HtmlHelper helper, string name)
{
var model = (TestModel)helper.ViewData.Model;
if(model.Helpers == null)
model.Helpers = new List<MyHelper>();
model.Helpers.Add(new MyHelper()
{
Name = name // add all the info i want from the helpers overloads
});
// .... helper logic here
return null;
}