I have a strange behavior that in my ASP.NET MVC project when I apply inline styling to html elements - they are not shown in the browser. But if I put the same styling in an external css file using a css class it will work (even putting the css class in a <style>
tag on the same page doesn't work.
Example:
NOT Working
<div style="height: 100px; width: 100px; background: red;">
ABC
</div>
NOT Working
<!DOCTYPE html>
<html>
<head>
<style>
.myClass {
height: 100px;
width: 100px;
background: red;
}
</style>
</head>
<body>
<div class="myClass">
ABC
</div>
</body>
</html>
Working
mystyle.css
.myClass {
height: 100px;
width: 100px;
background: red;
}
index.cshtml
<div class="myClass">
ABC
</div>
If I don't use a cshtml
file and just load a static html
file then all variations work.
Why is that? How do we fix it?
答案 0 :(得分:1)
您的代码示例不包含任何与MVC相关的内容,因此应该“按原样”发送到您的浏览器。 因此,如果它在一个简单的.htm文件中工作(它是),它也可以在.cshtml中工作,除非你忘了告诉我们一些关于“什么不工作”的事情。
根据您的浏览器,您可以使用F12或Ctrl U(etc)键查看页面源,并检查它是否与您在编辑器中放置的内容相匹配。 您还可以在Firefox中使用开发人员工具或Firebug来准确检查应用于哪个元素的样式。
此外,如果您的示例不完整,您的MVC网站可能会使用某些功能作为布局页面和一些默认的CSS,这会阻止您的内联样式完全按照您的预期进行。
答案 1 :(得分:0)
在一天结束时,在这种情况下真正重要的是发送到浏览器的代码,而不是用于将代码发送到浏览器的后端。如果它通过html
页面发送时有效,但是当您通过cshtml
页面发送时它不起作用,则在这两种情况下会向浏览器发送不同的内容。
因此,理解这个问题的关键是弄清楚有什么不同。使用开发人员工具查看通过html
页面发送的页面上的来源,并查看通过cshtml
页面发送的页面上的来源。比较两种情况下发送的html。鉴于示例代码非常小,应该很容易发现差异。一旦找到差异,就会对发生的事情有一个很好的线索。