Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is embedding CSS/jQuery code in C# code bad?

I see this type of code when looking through our working code base:

    private Button AddClearButton()
    {
        return new Button
                   {
                       OnClientClick =
                           string.Format(@"$('.{0}').css('background-color', '#FBFBFB');
                                   $('#' + {1}).val('');
                                   $('#' + {2}).val('');
                                   return false;", _className, _hiddenImageNameClientId, _hiddenPathClientId),
                       Text = LanguageManager.Instance.Translate("/button/clear")
                   };
    } 

or

            _nameAndImageDiv = new HtmlGenericControl("div");
            var imageDiv = new HtmlGenericControl("div");
            imageDiv.Attributes.Add("style", "width: 70px; height: 50px; text-align: center; padding-top: 5px; ");

            var nameDiv = new HtmlGenericControl("div");
            nameDiv.Attributes.Add("style", "width: 70px; word-wrap: break-word; text-align: center;");
            var image = new HostingThumbnailImage();

Disclaimer: I have not worked with CSS before. but I heard that we should separate css, js, html, C#, other than put them together.

so, is the above code bad? If yes, how is the better approach?

like image 712
Quan Mai Avatar asked May 18 '11 04:05

Quan Mai


People also ask

Can we write C# code in jQuery?

You can't. C# code runs entirely and only on the server, never the client. Javascript code runs only on the client.

What is the use of CSS () method in jQuery?

jQuery css() Method The css() method sets or returns one or more style properties for the selected elements. When used to return properties: This method returns the specified CSS property value of the FIRST matched element.

What is jQuery code?

jQuery is a lightweight, "write less, do more", JavaScript library. The purpose of jQuery is to make it much easier to use JavaScript on your website. jQuery takes a lot of common tasks that require many lines of JavaScript code to accomplish, and wraps them into methods that you can call with a single line of code.

Where do I put jQuery code in HTML?

Step 1: Firstly, we have to open that Html file in which we want to add the jQuery using CDN. Step 2: After then, we have to place the cursor between the head tag just before the title tag. And, then we have to use the <script> tag, which specify the src attribute for adding.


4 Answers

Off the top of my head I can think of a couple of issues, non fatal however.

In no particular order:

  1. You lose the ability to cache your JavaScript files, on either the server or on the client.
  2. You increase the side of your page. If every button has a lot of embedded JavaScript, then the page size, thus load times, are increased.
  3. Debugging will become extremely difficult.
  4. Unobtrusive JavaScript is your friend!
  5. Maintenance becomes more complex as you need to remember where in the C# code that the hard-coded JavaScript strings are.
  6. Intellisense is lost. Visual studio has a fantastic JavaScript editor, you lose all of that functionality by hard-coding the strings
  7. Did I mention Unobtrusive JavaScript is your friend!
  8. You lose the benefits of separation of functionality.
  9. If you have duplicate buttons with the same functionality, then you have duplicate code.

I'm sure there is a bunch I have missed.

like image 195
Alastair Pitts Avatar answered Oct 14 '22 16:10

Alastair Pitts


That isn't CSS but JavaScript, using the jQuery library. You are right to be suspicious, there are several "smelly" parts with this code:

  • Use of the OnClientClick results in an onclick="" attribute, which is less nice than binding the event. This is done dynamically, suggesting it happens multiple types.
  • Use and hard-coding of background-color - a CSS class would be much better, this color is probably duplicated many times in the code or the CSS files, and require a lot of work to be changed (redeploying the site code, rather then relying on resource files). A better approach is to use CssClass:

    imageDiv.CssClass = "imageDiv";

    and having in your CSS file:

    .imageDiv { width: 70px; height: 50px; text-align: center; padding-top: 5px; }

    this allows you to easily change the design, and having different imageDiv styled best on its context (for example, it can be smaller when it's in the sidebar, using the selector .sidebar .imageDiv)

  • Use of String.Format with JavaScript/CSS isn't pretty. For example, this is valid in JavaScript (and jQuery supported): .css({'color': '#FBFBFB', 'border-color':"green"}). With this code, it should be written as .css({{'color': '#FBFBFB', 'border-color':""green""}}) - escaping double quotes for the string, and curly braces for String.Format.

  • As you've mentioned, no separation of data/presentation/behavior.
like image 27
Kobi Avatar answered Oct 14 '22 16:10

Kobi


The generated code is Javascript actually, although it manipulates the CSS of some elements.

I'd say the best way would be to execute it at the loading of the page. If all you need is to bind a function to click event, you can do it all in Javascript/JQuery, with something like this:

$("#<%= this.TheButton.ClientID %>").click(function () {
    $("...").css("...", "...");
    // ...
});

I suspect ASP.NET currently simply generates a button with onclick=..., which is generally considered as a bad practice for Javascript programming, but it's not a huge problem.

The general problem here, in my opinion, is that the view and model logic are probably mixed together, but it's difficult to avoid it in traditional ASP.NET.

like image 41
Bastien Léonard Avatar answered Oct 14 '22 16:10

Bastien Léonard


The answer to the point:

Is the above code bad?

Bad, in the sense "bad programming practice", YES. Definitely bad.

What is the better approach?

The better approach is to split your code into

  • Event generating component (You dont have to worry about this)

  • Event listener(Which you will have to code)

Why is it a better approach?

Because its good programming practice and this brings in a ton of advantages. This is a subject by itself, which all graduates have to study these days. :D

like image 31
Augiwan Avatar answered Oct 14 '22 16:10

Augiwan