在 C# 代码中嵌入 CSS/jQuery 代码不好吗?
我在查看我们的工作代码库时看到了这种类型的代码:
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")
};
}
或
_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();
免责声明:我以前没有使用过 CSS。但我听说我们应该把css、js、html、C#分开,而不是把它们放在一起。
那么,上面的代码是不是很糟糕?如果是,更好的方法是什么?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(11)
我突然想到几个问题,但并不是致命的。
排名不分先后:
我确信我错过了很多。
Off the top of my head I can think of a couple of issues, non fatal however.
In no particular order:
I'm sure there is a bunch I have missed.
这不是 CSS,而是 JavaScript,使用 jQuery 库。 有几个“smelly”部分:
OnClientClick
会产生onclick=""
属性,该属性不如绑定事件好。这是动态完成的,表明它发生多种类型。使用和硬编码
background-color
- CSS类会更好,这种颜色可能在代码或CSS文件中重复很多次,并且需要大量工作才能被更改(重新部署站点代码,而不是依赖资源文件)。更好的方法是使用 CssClass:并在 CSS 文件中包含:
这使您可以轻松更改设计,并在其上下文中设置最佳的不同
imageDiv
样式(例如,使用选择器.sidebar 在侧边栏中时它可以更小) .imageDiv
)在 JavaScript/CSS 中使用
String.Format
并不漂亮。例如,这在 JavaScript 中有效(并且支持 jQuery):.css({'color': '#FBFBFB', 'border-color':"green"})
。使用此代码,应将其编写为.css({{'color': '#FBFBFB', 'border-color':""green""}})
- 转义双引号字符串,大括号表示 String.Format。That isn't CSS but JavaScript, using the jQuery library. You are right to be suspicious, there are several "smelly" parts with this code:
OnClientClick
results in anonclick=""
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:and having in your CSS file:
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.生成的代码实际上是 Javascript,尽管它操纵了某些元素的 CSS。
我想说最好的方法是在页面加载时执行它。
如果您需要的只是将一个函数绑定到单击事件,那么您可以在 Javascript/JQuery 中完成这一切,如下所示:
我怀疑 ASP.NET 当前只是生成一个带有 onclick=... 的按钮,这通常被认为是对于 Javascript 编程来说这是一个不好的做法,但这并不是一个大问题。
在我看来,这里的普遍问题是视图和模型逻辑可能混合在一起,但在传统的 ASP.NET 中很难避免它。
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:
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.
回答到重点了:
The answer to the point:
以这种方式实现此 JQuery 的原因很可能是由于必须引用服务器端控件 Id(_hiddenImageNameClientId、_hiddenPathClientId),这在 .NET 4 之前需要做一些工作。 (参见.NET 4 中的客户端 ID)
就“正确性”而言,我认为这是不正确的,因为我很想更喜欢在 JavaScript 中看到定义良好的客户端层来定义此单击事件。在我看来,混合服务器和客户端代码“闻起来”很糟糕,并且会破坏 SoC。
Most likely the reason this JQuery was implemented in such was a way was due to having to reference server side control Ids (_hiddenImageNameClientId, _hiddenPathClientId), which, prior to .NET 4 was a bit of work. (See Client Ids in .NET 4)
As far as "correctness", I'd consider this improper as I'd much prefer to see a well defined client side layer in javascript defining this click event. Mixing server and client side code "smells" bad to me and breaks SoC IMO.
我不喜欢在代码中嵌入 CSS。在我看来,这两种情况下更好的方法是向元素添加一个类,然后将 CSS 放入 CSS 文件中。在你的第一个例子中,
背景颜色是用javascript更改的,我会添加一个类“.addClass('selected')”(或toggleClass),其名称有意义。在第二个示例中,删除 CSS 并添加一个类 .Attributes.Add("class", "xxx")。
你的 CSS 文件将包含这样的内容:
我不喜欢在 c#/javascript 中操作颜色/边框等,因为随着项目的增长,你的演示文稿信息最终会遍布各处,并且更改或覆盖颜色变得很困难。
I don't like embedding CSS in code. A better approach in both cases in my view is to add a class to the element and then have the CSS in a CSS file. In your first example, the
background color is changed with javascript, I would add a class ".addClass('selected')" (or toggleClass) with a name that makes sense. In the second example remove CSS and add a class instead .Attributes.Add("class", "xxx").
Your CSS file will contain stuff like this:
I don't like manipulating colors/borders and such in c#/javascript because as the project grows, your presentation information ends up all over the place and changing or overriding a color becomes difficult.
第一个示例实际上是在单击事件触发时运行 JavaScript (jQuery)。第二个只是添加内联样式。我敢打赌这种方法是用来获取客户端 id 引用的(这在 .net 4.0 之前是很困难的)——尽管,还有其他方法可以使用纯 JavaScript 来获取它。
有些人会说这没关系,另一些人会说这是不好的做法并且丑陋。这实际上取决于您的编程风格。而且它绝对不是致命的。
优点:
- 不需要单独的文件
- 更快的开发(可以说)
缺点:
- 层之间没有明显的分离
- 随着项目变大,难以维护和调试
可能还有更多,但这就是我现在能想到的。
就我个人而言,我会远离这种代码。它使调试和维护变得更加复杂,并且对于接触您的代码的其他程序员来说不容易理解(特别是如果您有仅使用 javascript 和仅使用 C# 的程序员)。但这是经验丰富的程序员无法处理的,尤其是在小型项目上。
The first example is actually runs a javascript (jQuery) when the click event is fired. The second is just adding inline styles. I bet this approach was used to get the client id reference (which was difficult pre-.net 4.0) - although, there are other ways to get this using pure javascript.
Some would say its okay, others would say its bad practice and ugly. It depends on your programming style really. And its definitely not fatal.
Pros:
- No separate file needed
- faster development (arguably)
Cons:
- no clear separation of layers
- difficult to maintain and debug as the project grows bigger
There's probably more, but that's all I can think of right now.
Personally, I'd stay away from this kind of code. It makes debugging and maintenance a bit more complicated and its not easy to understand for other programmers that touch your code (especially if you have javascript-only and C#-only programmers). But its nothing that a seasoned programmer can't handle, especially on small projects.
我的回答是一些问题:
有很多内容需要讨论来回答这些问题以及一些因情况而异的注意事项。
简短的回答:将其混合是一种不好的做法。优先选择 css 类而不是内联样式。您还可以使用 jquery 的选择器根据 css 类或 id 将动态行为附加到 html 元素。此外,您可以根据包含关系有不同的行为。
My answer are some questions:
There is plenty to go over to answer those questions and some considerations that vary x scenario.
Short answer: it is a bad practice mixing it up. Favor css classes over inline styles. You can also use jquery's selector to use attach dynamic behaviors to html elements based on css classes or ids those have. Additionally you can have different behaviors based on a containment relationship.
这段代码调试起来会非常烦人。您询问了一个更好的解决方案,看来这里所做的一切都可以只用 javascript 来完成。
如果您绝对需要 C# 逻辑来执行此操作,我会将所有 javascript 代码包装到一个函数中,并从您的代码隐藏中专门调用该函数。
This code would be very annoying to debug. You asked about a better solution, It appears that everything that is being done here could be done with just javascript .
If you absolutely need C# logic to do this I would wrap all the javascript code into a function and call that function exclusively from your code-behind.
第一个示例实际上是在单击事件触发时运行 JavaScript (jQuery)。第二个只是添加内联样式。我敢打赌这种方法是用来获取客户端 id 引用的(这在 .net 4.0 之前是很困难的)——尽管,还有其他方法可以使用纯 JavaScript 来获取它。
有些人会说这没关系,另一些人会说这是不好的做法并且丑陋。这实际上取决于您的编程风格。而且它绝对不是致命的。
优点: - 不需要单独的文件 - 更快的开发(可以说)
缺点: - 没有明确的层分离 - 随着项目变大,难以维护和调试
可能还有更多,但这就是我现在能想到的。
就我个人而言,我会远离这种代码。它使调试和维护变得更加复杂,并且对于接触您的代码的其他程序员来说不容易理解(特别是如果您有仅使用 javascript 和仅使用 C# 的程序员)。但这是经验丰富的程序员无法处理的,尤其是在小型项目上。
The first example is actually runs a javascript (jQuery) when the click event is fired. The second is just adding inline styles. I bet this approach was used to get the client id reference (which was difficult pre-.net 4.0) - although, there are other ways to get this using pure javascript.
Some would say its okay, others would say its bad practice and ugly. It depends on your programming style really. And its definitely not fatal.
Pros: - No separate file needed - faster development (arguably)
Cons: - no clear separation of layers - difficult to maintain and debug as the project grows bigger
There's probably more, but that's all I can think of right now.
Personally, I'd stay away from this kind of code. It makes debugging and maintenance a bit more complicated and its not easy to understand for other programmers that touch your code (especially if you have javascript-only and C#-only programmers). But its nothing that a seasoned programmer can't handle, especially on small projects.
我相信很多人都给出了为什么这是一种可怕的方法的充分理由。它确实有效,很多事情也是如此,但这并不意味着你应该继续这样做。
我要在这里插入我自己的博客和目的一个阻止您编写这种特定类型的代码的解决方案,因为我过去常常做这样的事情,而自己却没有更好的解决方案。
在我的博客文章中,我还链接到我不久前提出的一个有关此问题的问题。它展示了如何使用它来完全避免这种类型的依赖性。如果您发现很难理解我的意思,我也很乐意回答有关此方法的任何问题。
I believe a lot of people have given great reasons why this is a horrible approach. It does work yes, so does a lot of things, that doesn't mean you should keep doing it this way.
I'm gonna plug my own blog here and purpose a solution to stop you from writing this particular type of code because I used to do things like this without having a better solution myself.
In my blog post, I also link to a SO question I made about this a while back. It shows how this can be used to completely avoid this type of dependency. I'll also happily answer any question regrading this approach If you find that it's difficult to understand what I'm getting at.