[英]Can i programmatically get a list of the helpers within an MVC 3 Razor view?
As the title states. 如标题所述。 I have an MVC 3 Razor view which i would like to programmatically instantiate and obtain a list of it's Html helpers.
我有一个MVC 3 Razor视图,我想以编程方式实例化并获取它的HTML帮助器列表。
anyone have any good suggestions on how to approach this? 有人对如何解决这个问题有什么好的建议吗?
Thanks in advance 提前致谢
I was able to achieve this by executing a custom view result and updating the model from my html helper. 我能够通过执行自定义视图结果并从html帮助器中更新模型来实现此目的。
Action Method: 动作方法:
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
}
View Result: 查看结果:
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);
}
}
Helper: 帮手:
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.