我不确定如何表达我的问题,所以我基本上希望能够在ASP.NET MVC 3中做这样的事情:
@myJsHtmlCustomCode
{
<div><h1>Title</h1></div>
}
myJsHtmlCustomCode
块中的任何内容都会被我编写的一些自定义JavaScript / HTML代码包围。
我知道我可以在代码中使用myJsHtmlCustomCode.Begin()
和myJsHtmlCustomCode.End()
之类的内容,但这不会提供相同的格式结构。
如果有人知道类似的方法来实现相同的目标,并获得自动大纲/缩进格式,那就太棒了。
仅供参考,我希望@myJsHtmlCustomCode
围绕代码,例如,另一个<div id="myTestId" onclick="thisClickEvent"></div>
,结果代码看起来像...... {/ p>
<div id="myTestId" onclick="thisClickEvent">
<div><h1>Title</h1></div>
</div>
答案 0 :(得分:2)
您可以将代码包装在实现IDisposable的对象中,就像使用@using (Html.BeginForm())
您的代码可能是这样的:
public class MyJsHtmlCustomCode : IDisposable {
private ViewContext _ctx;
public MyJsHtmlCustomCode (HtmlHelper html, /* other params */) {
_ctx = html.ViewContext;
/* Write begin tags */
_ctx.Writer.Write("html => opening tags"); }
public Dispose() {
_ctx.Writer.Write("html => closing tags");
}
}
和扩展名:
public static MyJsHtmlCustomCode BeginMyJsHtmlCustomCode(this HtmlHelper html /* other params */) {
var result = new MyJsHtmlCustomCode(html);
return result;
}
用法:
@using(Html.BeginMyMyJsHtmlCustomCode()) {
<div>This is surrounded by your code </div>
}
You can use Razor Templated Delegates:
@{
Func<dynamic, object> b = @<strong>@item</strong>;
}
<span>This sentence is @b("In Bold").</span>
<div>@b(
@<span>
@DateTime.Now
</span><span>Example of more complex logic
</span>
)</div>
答案 1 :(得分:1)
虽然我必须承认我并不完全理解您的问题,但每当我需要在.Net MVC 3中进行编程自定义HTML操作时,我都会使用Html Agility Pack。
答案 2 :(得分:0)
您可以使用@section获得所需的结果吗?
例如:在一个cshtml中,可能是_Layout:
<script type="text/javascript">
// whatever you want
// more whatever you want
@RenderSection("jsCode", false)
// even more whatever you want
</script>
然后在实际视图中使用cshtml:
@section jsCode{
<div><h1>Title</h1></div>
}
您可以使用js位的部分视图,例如