Page 1 of 1

Razor helpers

#1 Nakor  Icon User is offline

  • Professional Lurker
  • member icon

Reputation: 441
  • View blog
  • Posts: 1,488
  • Joined: 28-April 09

Posted 20 April 2011 - 05:33 AM

For those of you familiar with ASP.Net and wanting to get familiar with WebPages (.cshtml extensions) that use the razor template the first thing you might notice is that there are no toolbox controls provided. However, don't get too discouraged before you even get started, while there are not WebControls there are HtmlHelpers that work in a similar fashion. So let's take a look at some of the standard helpers.


// TextBox:
@Html.TextBox(name: "TextBox1", value: "Testing", htmlAttributes: new {id="TextBox1", @class="TextBoxCss"})
// produces
<input class="TextBoxCss" id="TextBox1" name="TextBox1" type="text" value="Testing" />

//Label:
@Html.Label(labelText: "This is a test", attributes: new { id = "TextBox1", @class = "TextBoxCss" });
<label class="TextBoxCss" for="This is a test" id="TextBox1">This is a test</label>

// Radio Button
@Html.RadioButton(name: "RadioButton1", value: "SelectedValue", isChecked: false)
<input id="RadioButton1" name="RadioButton1" type="radio" value="SelectedValue" />



The parameter htmlAttributes is an optional object parameter used to set additional html attributes. Attributes that are also reserved keywords in C# must be preceded with the @ character as seen in the class attribute above or you will get a compiler error. It is also optional to name the parameters as I've done above using the "name: value" syntax. I've done so here so you can see which properties are being set. This is just a couple of the standard helpers that are available and you may be thinking that they really don't provide much benefit over just typing out the html, but let's take a look at a couple more helpers.

The WebGrid helper provides a way to easily format data into a table. This is great for displaying large amounts of data and this helper really cuts down on the amount of code you would otherwise have to write to create a table. After creating your connection string in your Web.Config all we need is a simple 3 lines to get the WebGrid working.

@{
    var DB = Database.Open("pubsConString");
    var grid = new WebGrid(DB.Query("select * from authors"));
    @grid.GetHtml()
}



For a little more information on using the WebGrid helper see this tutorial.

This was just a quick introduction to some of the standard helpers available using Razor for ASP.NET. There are more standard helpers and also many third party helpers available as well to simplify creating an html form and I'll dive more into those in the future.

Is This A Good Question/Topic? 0
  • +

Page 1 of 1