Aplying style to a list item dynamically in view - asp.net

I have got a list and I want to apply a different style to each item depending on it's Id. Below is my attempt to do that but unfortunately something is wrong. Any help will be very appreciated.
#foreach (var item in Model)
{
#if (#item.Id==0)
{
var css = "background-color:Aqua";
}
else if (#item.Id==1)
{
var css = "background-color:Red";
}
else
{
var css = "background-color:Green";
}
<div style="#css" class="box">
#item.Info
</div>
<div>
#item.Name
</div>
}

Your if condition is already in a code block(foreach code..). So no need of # . Also define the css varibale outside of your if-else blocks
#foreach (var item in Model)
{
var css="background-color:Green";
#if (#item.Id==0)
{
css = "background-color:Aqua";
}
else if (#item.Id==1)
{
css = "background-color:Red";
}
<div style="#css" class="box"> #item.Info </div>
<div> #item.Name </div>
}
Another solution is creating a css class name string inside your loop using your item.Id or item.Code(if that exists) and using that in your markup. With this approach, you may completely eliminate the if condition checking in your razor code, thus making this a much cleaner solution than the previous one.
#foreach (var item in Model)
{
<div class="box myClass-#item.Id">
#item.Name
</div>
<div> #item.Name </div>
}
And in your css class add the css classes as needed
.myClass-0
{
background-color:aqua;
}
.myClass-1
{
background-color:red;
}
.myClass-2
{
background-color:green;
}
Id's might change, so i recommend using some other properties like Code/Name etc.

First of all try setting a default style and bring var css out of the if block, then set the value according to your needs.
But you can also try a helper for that:
#helper styler(int id, String value){
var bg = "background-color:white" // as default
if(id == 1){
bg = "Another color";
}
else if (id == 2) {
// continue setting values
}
<span style="#bg">#value</span>
}
However, this is not really necessary as you can set the style inside of the for loop, but this approach reduce some code duplication.

Related

Protractor: Locating element that contains multiple divs and no unique css to identify them

Just wanted to share: If you are in a situation where there are no classes within a certain section and the value of that particular div cannot be hardcoded and changes, using protractor e2e framework I have managed to locate the specific div using this method:
Adding an example of html that does not have a class for every element
<div class="row">
<div class="page_banner">A Dude's Profile</div>
<div class="profile_details">
<div class="profile_name">
<h3>Tony Adams</h3>
</div>
<div>ta#bogus.com</div>
<div>0883424324</div>
</div>
</div>
In the case where you need to say identify that there is a unique mobile number, so the value is not consistent.
function mobileNumberAssert() {
element.all(by.css('.profile_details'))
.get(1) // number of divs in css
.getText()
.then(function(textFoundInCss) {
if(textFoundInCss > 10) {
return true;
console.log('there is a mobile number present with 10 digits');
} else {
return false;
}
});
}
For Debugging you can console log the "textFoundInCss" working your way to locate that particular div.
Since it seems like you are looking for an element based on the text you could use by.cssContainingText() to make this a lot easier.
const el = element(by.cssContainingText('div', `Text I'm looking for`);
el.isPresent().then(isPresent => {
if (isPresent) {
// do something ...
} else {
return false;
}
}

Hide a whole div with CSS with part of it is empty

Is there a way to hide a whole div if part of it is empty? For example if "dd" is empty as shown below can I hide the whole class "test" so the keyword Restrictions does not show either. I tried .test dd:empty { display: none; } but this does not work. thanks!
<div class="test"><dt>Restrictions:</dt>
<dd></dd></div>
I don't think there's any easy way to do what you're talking about with just CSS. Better to test it server-side if you can. But if you can't here's some JS that will do the job.
<script type="text/javascript">
// handles multiple dt/dd pairs per div and hides them each conditionally
function hideIfEmpty() {
// get all the elements with class test
var els = document.getElementsByTagName('dl');
// for every 'test' div we find, go through and hide the appropriate elements
Array.prototype.map.call(els, function(el) {
var children = el.childNodes;
var ddEmpty = false;
for(var i = children.length - 1; i >= 0; i--) {
if(children[i].tagName === 'DD' && !children[i].innerHTML.trim()) {
ddEmpty = true;
} else if(children[i].tagName === 'DT') {
if(ddEmpty) {
children[i].style.display = 'none';
}
// reset the flag
ddEmpty = false;
}
}
});
}
window.addEventListener('load', hideIfEmpty);
</script>
<div class="test">
<div style="clear: both;"></div>
<dl>
<dt>Restrictions:</dt>
<dd></dd>
<dt>Other Restrictions:</dt>
<dd>Since I have content, I won't be hidden.</dd>
</dl>
</div>
Just a fair warning: the code uses some functions that may not exist in older IE, such as Array.prototype.map, String.prototype.trim, and addEventListener. There are polyfills available for these and you could also write your own pretty easily (or just do it with a for loop instead).
CSS alone can't do that. Either, you need a javascript to retrieve empty elements and hide their parents, or your CMS applies special CSS classes if there's no content.
Put as an answer as requested by #Barett.
You could update your CSS to be
.test{
display: none;
color: transparent;
}
This would make the text transparent too, but display:none should hide it anyway.
To make the div with the id test ONLY show when the dd tag is EMPTY, and you can use jQuery, try the following JavaScript along with the CSS:
if($("dd").html().length ==0)
{show();
}
Note: this solution requires jQuery, which is a JavaScript library.

ASP MVC - CSS Image Sprites into a View

I have a huge css file (Content/Site.css) which includes also more than 200 lines of spirits.
I wanna make a View/PartialView which shows all my sprites images ( many divs ) .
How I do it?
How to read and parse css file in code behind from a controller and then put my result into a ViewBag?
Or there is no need to parse from server side and just show it from client side?
div.feedImgPop,
div.feedImg,
div.feedImgList { background: url("http://xxx/Sprite.jpg") top left no-repeat; }
div.a{ background-position:0 0; }
div.b{ background-position:0 -43px; }
... 200 lines..
asp net mvc 4.5
Update :
Splited CSS file into 2 files , sprite and the rest
Used CSS Parser to read the sprite css file from a controller
Show the sprite images as shown below
I used this css parser
Controller :
public ActionResult Admin()
{
parser.ReadCSSFile(Server.MapPath("~/Content/Sprite.css"));
var cssItems = new List<String>(cssList.Count);
foreach (var item in cssList) cssItems.Add(item.Key.Replace("div.", ""));
ViewBag.items = cssItems;
return View();
}
View : ( CSS Solution - I use this )
<div class="wrapper">
<div class="container">
#foreach (var item in ViewBag.items)
{
string className = "imgContainer imgHover feedImgPop " + #item;
<div class="#className" onClick="adminChooseSpriteImage('#className')"></div>
}
</div>
</div>
View : (Table Solution - 10 items each row ; previous test )
<div id="feedsContainer">
#{
int rowNumber = 1;
<table>
<tr>
#foreach(var item in ViewBag.items)
{
if (rowNumber % 11 == 0)
{
<tr></tr>
}
else
{
string className = "imgContainer imgHover feedImgPop " + #item;
<td><div class="#className"></div></td>
}
rowNumber++;
}
</tr>
</table>
}
</div>

Why #Html.Action when is inside in a block, it does not show its Html?

I spend two hours to realized that if I put a Action inside of a block, it does not show the partial view.
<div>
#if (ViewBag.Tab == "summary")
{
Html.Action("Summary");
}
else { ... }
</div>
But if I do the following it works, but if not what I want:
<div>
#if (ViewBag.Tab == "summary")
{ <div>
Html.Action("Summary");
</div>
}
else { ... }
</div>
Is there a way to show the partial view using the first option?
Neither of your examples would work properly. Html.Action returns an MvcHtmlString. You need to prefix it with an #:
#if (ViewBag.Tab == "summary")
{
#Html.Action("Summary"); // prefix with # works fine.
}

MooTools 1.1, how to get id of class and apply a style

I need to get the id attribute of a class and apply a style based on that id.
So for instance, 3 list items each with the class "typo", one id is "application", another id is "application_osx", and the final id is "application_osx_terminal"
The class "typo" is handled by CSS, but I would need to assign a background image based on the ID name.
So if the id happens to be "application_osx" or "someotherid", it would automatically have this CSS applied to it
#application_osx { background: url(/path/to/image/application_osx.png) }
#someotherid { background: url(/path/to/image/someotherid.png) }
I'm trying to use MooTools 1.1 for this.
I guess it would look like this barebones
<html>
<head>
<title>Blah</title>
<script src="path/to/mootools.js"></script>
<script>
A SCRIPT THAT PRINTS OUT:
#application_osx { background: url(/path/to/image/application_osx.png) }
#someotherid { background: url(/path/to/image/someotherid.png) }
BASED ON THE CLASS "TYPO"
</script>
</head>
<body>
<ul>
<li id="application_osx" class="typo">Application OSX</li>
<li id="someotherid" class="typo">Someotherid</li>
</ul>
</body>
</html>
$$('.typo').each(function(el){
el.setStyle('background-image', 'url(/path/to/'+el.id+'.png)')
});
Should do the trick, if I understand well…
why can't you define the rules in your css file? if you need to dynamically produce rules and append to the document head then you need something like this
for mootools 1.2.x
http://www.jsfiddle.net/dimitar/G5ywF/1/
var StyleWriter = new Class({
// css classes on the fly, based on by Aaaron Newton's version
createStyle: function(css, id) {
try {
if (document.id(id) && id) return;
var style = new Element('style', {id: id||'',type:'text/css'}).inject(document.getElement('head'));
if (Browser.Engine.trident)
style.styleSheet.cssText = css;
else
style.set('text', css);
} catch(e) {
console.log("failed:", e);
}
}
});
use:
new StyleWriter().createStyle("#rule { blah; }\n#rule2 { blah... }\n", "mystyles");
edit it was just brought to my attention you are on mootools 1.11 so
http://www.jsfiddle.net/G5ywF/4/
class version for 1.11 with slight changes:
var StyleWriter = new Class({
// css classes on the fly, based on by Aaaron Newton's version
createStyle: function(css, id) {
try {
if ($(id) && id) return;
var style = new Element('style', {id: id||'',type:'text/css'}).inject(document.getElement('head'));
if (window.ie)
style.styleSheet.cssText = css;
else
style.setHTML(css);
} catch(e) {
console.log("failed:", e.message);
}
}
});
tested the 1.11 class in FF 3.6x, Chromium 5 and IE7

Resources