ASP.Net MVC 3 Razor Response.Write position

狂风中的少年 提交于 2019-12-03 10:04:49

A Razor view is rendered inside-out. Basically it writes content to temporary buffers which get written to the response stream when the top most layout page is reached. Thus, writing directly to the response stream from your HtmlHelper extension, will output it out of order.

The solution is to use:

helper.ViewContext.Writer.Write("<div id=\"" + pagelet.Container + "\"></div>");

Change your method to be not void, but returning MvcHtmlString

public static MvcHtmlString OutputText(this HtmlHelper helper, string text) {
     return New MvcHtmlString(text);
}

Than use this as you used to

<div id="textHolder">
    @Html.OutputText("FooBar");
</div>

Idea is inspired by the fact that almost every input(and other) extension method in MVC returns MvcHtmlString

You should use the ViewBag and put the string in there, then output it.

In controller:

ViewBag.Foo = Bar;

In view:

<div>
@ViewBag.Foo
</div>

I wouldn't bother doing it. The end result you want is t have FooBar written within your div, so why not just write it into your div? Why do you need to use Response.Write?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!