是否可以在控制器中使用HtmlHelper,例如获取TextBox(...)方法?并不是说我不能写自己生成的html,但我只是想了解它是如何工作的,所以我可以创建最好的解决方案.
Mau*_*fer 41
下面是改编自一个例子此:
var h = new HtmlHelper(new ViewContext(ControllerContext, new WebFormView("omg"), new ViewDataDictionary(), new TempDataDictionary()), new ViewPage());
h.TextBox("myname");
Run Code Online (Sandbox Code Playgroud)
请注意,这是一个黑客,它可以做,但我认为没有任何理由这样做...
Vit*_*kov 30
你可以使用这样的方法:
public static HtmlHelper GetHtmlHelper(this Controller controller)
{
var viewContext = new ViewContext(controller.ControllerContext, new FakeView(), controller.ViewData, controller.TempData, TextWriter.Null);
return new HtmlHelper(viewContext, new ViewPage());
}
public class FakeView : IView
{
public void Render(ViewContext viewContext, TextWriter writer)
{
throw new InvalidOperationException();
}
}
Run Code Online (Sandbox Code Playgroud)
HtmlHelper是View机制的一部分,应该被视为与MVC的Controller和Model部分分开.我不确定你为什么要在控制器内部生成控件,因为它的作用是将数据传递给视图进行渲染.
我不是说你无法实现它,但是为了好的设计它会更好.
你能解释一下你想要实现的目标,然后我们可以用"MVC方式"来做这件事吗?
using System.Web.Mvc;
using System.Web.Mvc.Html;
var h = new HtmlHelper<Effort>(new ViewContext(ControllerContext, new WebFormView(ControllerContext, "omg"), new ViewDataDictionary(), new TempDataDictionary(), new StringWriter()), new ViewPage());
h.DisplayFor(e => Model.Efforts[i].Content.Offer.Price1.Value)
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
54039 次 |
最近记录: |