Jun/091
Rendering HTML and Javascript in ASP.NET custom controls
Welcome to the ITCreatings Developers blogs!
So we are starting to write articles for developers. We plan to create a series of blog posts, where some of our .net, JavaScript and other techniques will be described. It is some tips about how we build our project, what technologies we use and how we extend some default Microsoft .NET functionality.
So, lets start with simple thing and I hope we will continue with many useful features and code samples.
A brief preview so far.
– We are creating custom DB layer (Ndb Library).
- We are creating custom web data handlers, an alternative for SOAP Web services or WCF Services.
- We are creating custom web controls, based on popular JQuery JavaScript framework and server side HTML and JavaScript generation.
This post is about how to simplify life of ASP.NET custom controls developer.
Let see what we have by default when try to create some web control.
writer.AddAttribute(HtmlTextWriterAttribute.Id, ID);
writer.AddAttribute(HtmlTextWriterAttribute.Class, CssClass);
writer.RenderBeginTag(HtmlTextWriterTag.Div); //</div id="someID" class="someClass">
writer.RenderEndTag(); //</div>
writer.Write("\r\n");
This is just to render div html tag, and imaging what if we need to render complex Table or something else.
The simpler way is
writer.Write("<div id=’" + ID + "’ class=’" + CssClass + "’></div>");
This is just one code line instead of five above, but when we need to create something really usable in our projects this will be not one hundred of code lines. I think it’s boring to write such kind of code, not saying about understand it in future.
Another situation – we need to render some JavaScript code. This is the same story:
writer.Write("<script type=’text/javascript’ >\r\n");
writer.Write("function " + dataLoadFunction + @"(someID){");
writer.Write(@"
showLoading();
var params = { action: someAction, id: someID};
someLoadFunction(’" + WebServiceName + @"’, params,
function(response) {
if (response != undefined)) {
" + dataBindFunction + @"(response);
hideLoading();
}
else showError();
});
");
writer.Write("} \r\n");
writer.Write("</script>");
And this will render just (don’t mind about formatting):
<script type="text/javascript">
function dataLoadFunction(someID) {
showLoading();
var params = {action: ’someAction’, id: someID };
someLoadFunction(‘loadDataService’, params,
function(response) {
if (response != undefined)) {
bindData(response);
hideLoading();
}
else showError();
});
}
</script>
In my practice of developing web custom controls I had to write a lot of such code – HTML and JavaScript.
And believe me there is no fun when you need to support this controls, refractor, add some new logic or else.
So now an interest part – how we changed the things about writing code, as in examples above.
Check this out, our JS and HTML helper classes in action.
// writer is and HtmlTextWriter instance.
Html Html = new Html(writer);
Html.Div(Html.Attributes("id", ID, "class", CssClass), () =>
{
writer.Write("You can still use wirter
object to render contents or…");
// … use our cool helper class
// to render tags with annonimous functions.
Html.A(Html.Attributes("href", "http://www.itcreatigs.com"),
() => Html.Write("Click here."));
// most common method
Html.Tag(HtmlTextWriterTag.Form,Html.Attributes("action","./ "),
() => {
// some Html.Input overloads
Html.TextBox("name", "Name", "value", "Nikolay Grachov");
Html.Intput(Html.Attributes("type", "password", "name", "Password"));
Html.Intput("submit", "Submit", "Login");
}
});
This will render:
<div id="someID" class="someClass">
You can still use wirter
object to render contents or…
<a href="http://www.itcreatings.com">Click here.</a>
<form action="./">
<input type="text" name="Name" value="Nikolay Grachov" />
<input type="password" name="Password" />
<input type="submit" name="Submit" value="Login" />
</form>
</div>
And what about JavaScript? There is more complex stuff, see what we have so far:
Js js = new Js(writer);
// render Script tag
Html.Script(Html.Attributes("type", "text/javascript"),()=>
{
// function declaration
js.Function("dataLoadFunction", "someID",()=>
{
// and now let’s see what we can use with JS helper..
// call function without parameters
js.Call("showLoading");
// init json object
js.Var("params", js.JsonParams("action", "’someAction’", "id","someID"));
// call function with 2 parameters,
// where the second is callback(response)
js.Call("someLoadFunction", "params", "response",
() => {
// IF/ELSE statement
js.If("response != undefined", ()=>
{
// more calls
js.Call("someDataBindFunction","response");
js.Call("hideLoading");
}).Else(()=>
{
js.Call("showError");
});
});
});
});
That’s it! What do you think? Course it’s just simple examples, all these helper methods has many overloads, which can render allmost all js code you need.
Like JQuery?
Me too, so:
Html.Script(Html.Attributes("type", "text/javascript"),()=>
{
js._("document").Ready(()=>
{
js._("#someID")
.Click(() => js.Call("someClickEventHandler"))
.Event("moseover", () => js.Call("someMouseEventHandler"))
.Hide()
.Show()
.Attr("myAttr", "myAttrValue").rn();
js.Var("someHtml", ()=> js._("#someDiv").Html());
js._("#someDiv").Empty().rn();
});
});
This will render:
<script type="text/javascript">
$(document).ready(funtion(){
$("#someID")
.click(function () { someClickEventHandler(); })
.moseover(function () { someMouseEventHandler(); })
.hide()
.show()
.attr("myAttr", "myAttrValue");
var someHtml = $("#someDiv").html();
$("#someDiv").empty();
});
</script>
Was this usefull ?
I think you notice that not all code looks more simpler and readable then usual ones.
But you shoud undrstand – that class is nothing more then a tool which you can extend in many many ways.
Don’t like to write
Html.Script(Html.Attributes("type", "text/javascript"),()=>
{
});
Fine, write wraper to this function in your control and use just
Script(()=>
{
});
like I do that.
Anyway I hope this article will help you to extend you web controls techniques and write more and faster.
Link to download: HTML_JS_helpers.zip
See you in next posts, good luck!
July 27th, 2009
That is some inspirational stuff. Thanks for all the enthusiasm to offer such helpful information here.