(转载)ASP.NET MVC – Add CSS class Attribute

If you are a web developer, you probably are used to using the standard “class” attribute in your HTML. If you typically use ASP.NET Web Forms, you are probably used to using the CssClass property on your web server controls. But, if you are new to ASP.NET MVC like me, you may be surprised to learn that the HtmlHelper extension methods do not explicitly provide a parameter for your styling needs.  Instead, if you are using C#, you need to use the object initializer syntax introduced in C# 3.0. To cut to the chase, adding a “class” attribute to an input element generated by a HtmlHelper extension method looks like this:

<%= Html.TextBox(”myTextBox”, null, new{@class = “required”}) %>

Please notice how @class is in bold. The reason for this is because the @ prefix is necessary in this specific case because class is a keyword in C#. If you omit the @ prefix, you will receive a compile time error that says:

 

Compilation Error

Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.

Compiler Error Message: CS1513: } expected

 

The reasons for wanting to add CSS class information to your HTML elements are numerous. You may simply want to stylize your HTML elements. Or, you may want to prepare your elements to work with a JavaScript framework like JQuery. Regardless of the reason, if you would like to learn more about ASP.MVC, I recommend ASP.NET MVC in Action (or you could just skip MVC and learn Silverlight :) ). As someone that has traditionally written applications using the ASP.NET Web Forms approach I hope to write more about the challenges I come across. What challenges are you experiencing in ASP.NET MVC that you were comfortable overcoming with the ASP.NET Web Forms style?

 

原文链接:http://blog.ecofic.com/?p=311

posted on 2010-03-25 17:48  hzwang  阅读(1281)  评论(0编辑  收藏  举报

导航