Reputation: 2967
I'm not sure how to phrase my question, so I essentially want to be able to do something like this, in ASP.NET MVC 3:
@myJsHtmlCustomCode
{
<div><h1>Title</h1></div>
}
where anything in that myJsHtmlCustomCode
block would be surrounded with some custom JavaScript/HTML code that I wrote.
I know I could use something like myJsHtmlCustomCode.Begin()
and myJsHtmlCustomCode.End()
in my code, but that doesn't provide the same formatting structure.
If anyone knows of a similar way to achieve the same objective, and get the automatic outlining/indent formatting, that would be great.
Just for reference, I wanted the the @myJsHtmlCustomCode
to surround the code with for instance, another <div id="myTestId" onclick="thisClickEvent"></div>
for the resulting code to look like...
<div id="myTestId" onclick="thisClickEvent">
<div><h1>Title</h1></div>
</div>
Upvotes: 1
Views: 191
Reputation: 52501
You can wrap your code in an object that implements IDisposable, just like you use @using (Html.BeginForm())
Your code could be like this:
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");
}
}
and the extension:
public static MyJsHtmlCustomCode BeginMyJsHtmlCustomCode(this HtmlHelper html /* other params */) {
var result = new MyJsHtmlCustomCode(html);
return result;
}
Usage:
@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>
Upvotes: 2
Reputation: 357
Could you achieve your desired result using @section ?
e.g.: in one cshtml, possibly the _Layout:
<script type="text/javascript">
// whatever you want
// more whatever you want
@RenderSection("jsCode", false)
// even more whatever you want
</script>
Then in your actual view cshtml:
@section jsCode{
<div><h1>Title</h1></div>
}
You could possibly use a partial view for the js bit e.g.
Upvotes: 0
Reputation: 22655
While I must admit I do not completely understand your question, whenever I need to do programatic custom HTML manipulation in .Net MVC 3 I use the Html Agility Pack.
Upvotes: 1