Menu
  • HOME
  • TAGS

How to assign C# variable to CSS class variable in ASP.NET MVC ActionLink

Tag: c#,css,asp.net-mvc,razor,dynamic-css

In the ActionLink code below, how can I assign a C# string variable to @class in the view in ASP.NET MVC 5?

@Html.ActionLink("Manage List", "Index", new { @class = "DynamicClassName" });

I want to replace the static string @class = "DynamicClassName" with something dynamic, similar to @class = @myChangingColorClass

// Error 
// yes, myChangingColorClass is declared C# valid string 
@Html.ActionLink("Manage List", "Index", new { @class =  @myChangingColorClass });

Best How To :

This can be do by two ways one is by setting value in ViewModel class or by setting value in ViewBag, ViewData or TempData.

Way 1) Preffered way Strongly Typed: Set css class name to viewmodel class attribute:

Class Student
{
  public ID BIGINT {get; set;}
  ... //other properties

}

Class StudentViewModel : Student
{
   public CssClass string {get; set;}
}

//controller action

public ActionResult Index(){
  StudentViewModel objModel; 
  //initialize model

  objModel.CssClass = "myCssClass"; //set css class name to viewmodel 
  return View(objModel);
}

//in view use code like below:

@model namespace.StudentViewModel;
@Html.ActionLink("Manage List", "Index", new { @class =  Model.CssClass })

Way 2) Set css class name to viewbag / viewdata / tempdate. But this is not prefered.

//controller action

public ActionResult Index(){

  ViewBag.CssClass = "myCssClass"; //set css class name to ViewBag
  //or
  ViewData["CssClass"] = "myCssClass"; //set css class name to ViewData
  //or
  TempData["CssClass"] = "myCssClass"; //set css class name to TempData

  return View();
}

//in view use code like below:

@Html.ActionLink("Manage List", "Index", new { @class =  @ViewBag.CssClass })
//Or
@Html.ActionLink("Manage List", "Index", new { @class =  @Convert.toString(ViewData["CssClass"]) })
//Or
@Html.ActionLink("Manage List", "Index", new { @class =  @Convert.toString(TempData["CssClass"]) })

Please let me know, is this works for you?

Google map infowindow position on custom marker

javascript,css,google-maps,google-maps-api-3

Set the pixelOffset of the InfoWindow appropriately: From the documentation on InfoWindows pixelOffset | Type:Size | The offset, in pixels, of the tip of the info window from the point on the map at whose geographical coordinates the info window is anchored. If an InfoWindow is opened with an anchor,...

tag in HAML

html,css,haml

HAML equivalent is %i{class:"fa fa-search"} You can look at http://codepen.io/anon/pen/BNwbEP and see the compiled view ...

How to remove all the borders of a selectbox?

jquery,html,css,drop-down-menu

Firefox has some problems with select-background. You can try this code - it'll remove the arrow, and then you can add a background image with your arrow (I took an icon from google search, just put you icon instead) I get this on FireFox (You can use any arrow icon...

How To Check Value Of String

javascript,css,string,numeric

document.GetElementById("tombolco").style = "display:block"; That's not the right way. This is document.getElementById("tombolco").style.display = 'block'; Also note that it is getElementById, not with a capital G. Same with 'none',Rest of your code is fine. Fiddle...

Multiple Threads searching on same folder at same time

c#,multithreading,file-search

Instead of using ordinary foreach statement in doing your search, you should use parallel linq. Parallel linq combines the simplicity and readability of LINQ syntax with the power of parallel programming. Just like code that targets the Task Parallel Library. This will shield you from low level thread manipulation and...

System.net.http.formatting causing issues with Newtonsoft.json

c#,asp.net,asp.net-mvc,json.net

Does the assemblyBinding tag have proper xmlns schema? Check if the issue you are encountering is same as Assembly binding redirect does not work

deployment of a site asp.net and iis

c#,asp.net,iis

There are several domain providers like: godaddy, name etc you can use to buy a domain name. These providers also provide you steps to map the domain name to your website. Check out this link for example. This link explains domain name configuration in details.

Convert contents of an XmlNodeList to a new XmlDocument without looping

c#,xml,xpath,xmldocument,xmlnodelist

If you're happy to convert it into LINQ to XML, it's really simple: XDocument original = ...; // However you load the original document // Separated out for clarity - could be inlined, of course string xpath = "//Person[not(PersonID = following::Person/PersonID)]" XDocument people = new XDocument( new XElement("Persons", original.XPathSelectElements(xpath) )...

Changing font-size of
  • on wordpress
  • css,wordpress,html-lists

    I think you have style inheritance from upper element, check it with dev. tools in browser. You can also try to set inline style for: <li style: "font-size: 22px;">Name 1</li> or add !important in your css file, like this: td > ul li { font-size: 22px !important;"> } ...

    Marshal struct in struct from c# to c++

    c#,c++,marshalling

    Change this: [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 36)] private string iu; to this: [MarshalAs(UnmanagedType.LPStr)] private string iu; Note that this code is good only to pass a string in the C#->C++ direction. For the opposite direction (C++->C#) it is more complex, because C# can't easily deallocate C++ allocated memory. Other important thing:...

    How do I provide a collection of elements to a custom attached property?

    c#,wpf,binding

    I managed to get it working using an IMultiValueConverter like this: public class BorderCollectionConverter : IMultiValueConverter { public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture) { var borderCollection = new BorderCollection(); borderCollection.AddRange(values.OfType<Border>()); return borderCollection; } public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture) { throw new...

    CSS :hover that shows more than one image

    html,css,css3

    Okay so I have got a probable solution, the catch is, you won't be able to use img tags. You can use images as background-image and animate background on :hover NOTE: Fade in effect can be removed by playing with animation. HTML <div class="image-box"></div> CSS .image-box { height: 200px; width:...

    How to return result while applying Command query separation (CQS)

    c#,design-patterns,cqrs,command-query-separation

    In such scenario I usually go with generating new entity Ids on the client. Like this: public class ProductController: Controller{ private IProductCommandService commandService; private IProductQueryService queryService; private IIdGenerationService idGenerator; [HttpPost] public ActionResult Create(Product product){ var newProductId = idGenerator.NewId(); product.Id = newProductId; commandService.AddProduct(product); //TODO: add url parameter or TempData key to...

    Visual Studio Assembly force-installs Target Framework

    c#,.net,visual-studio-2013,.net-framework-version

    The targeted .NET version is the only version that the app will depend upon by default. Visual Studio will not automatically add higher and backwards compatible releases. Do this manually by adding other .NET versions to a configuration file: On the Visual Studio menu bar: Choose Project; Add New Item;...

    how can I add a column to IQueryable object and modify its values

    c#,.net,linq,grid,devexpress

    Simple example for using a non-anonymous class. public class MyLovelyClass { public Int32 Number { get; set; } public bool Selection { get; set; } } var packs = from r in new XPQuery<Roll>(session) select new MyLovelyClass() { Number = r.number }; gcPack.DataSource = packs; ...

    check if file is image

    c#,asp.net,asp.net-mvc

    You can't do this: string.Contains(string array) Instead you have to rewrite that line of code to this: if (file == null || formats.Any(f => file.Contains(f))) And this can be shortened down to: if (file == null || formats.Any(file.Contains)) ...

    Website showing differently in windows xp and mobile

    html,css

    The background colour changes when the browser width is less than 1200px wide. You have specified the background-color for the selector .td-grid-wrap within a media query: What you need to do is move the background-color property to the non-media-queried selector .td-grid-wrap or perhaps .td-page-wrap. ...

    Dynamically resize side-by-side images with different dimensions to the same height

    javascript,html,css,image

    If it's responsive, use percentage heights and widths: html { height: 100%; width: 100%; } body { height: 100%; width: 100%; margin: 0; padding: 0; } div.container { width: 100%; height: 100%; white-space: nowrap; } div.container img { max-height: 100%; } <div class="container"> <img src="http://i.imgur.com/g0XwGQp.jpg" /> <img src="http://i.imgur.com/sFNj4bs.jpg" /> </div>...

    C# Code design / Seperate classes for each TabControl

    c#,oop,architecture,software-design,code-design

    Place a UserControl on each tab.

    Div with the form of a pencil [duplicate]

    html,css,css-shapes

    .pencil{ width: 200px; height: 40px; border: 1px solid #000; position: relative; } .pencil:before{ content: ''; display: block; margin: 10px 0; width: 100%; height: 10px; border: 6px solid #000; border-width: 6px 0; } .pencil:after{ content: ''; display: block; height: 10px; border: 1px solid #000; border-width: 1px 1px 0 0; width:...

    Aligning StackPanel to top-center in Canvas

    c#,wpf,xaml,canvas

    If you don't want any input or hit testing on a certain element you should set the IsHitTestVisible property to false: <Grid> <Canvas Name="Canvas" Background="#EFECCA"> <DockPanel VerticalAlignment="Stretch" HorizontalAlignment="Stretch" Width="{Binding ActualWidth, ElementName=Canvas}" Height="{Binding ActualHeight, ElementName=Canvas}" MouseLeftButtonDown="DockPanel_MouseLeftButtonDown" TouchDown="DockPanel_TouchDown" Panel.ZIndex="2" Background="Transparent"> </DockPanel> <Button Width="50" Height="50"...

    How to send Ctrl+S through SendKeys.Send() method to save a file(save as dialog)

    c#,.net,windows,sendkeys

    I believe you need to use: SendKeys.SendWait("^(s)"); Instead of: SendKeys.SendWait("^%s?"); Have a look at https://msdn.microsoft.com/en-us/library/system.windows.forms.sendkeys.send(v=vs.110).aspx for more information....

    Collect strings after a foreach loop

    c#,xml,foreach

    Yep, you need to do the adding within the loop. I'd use a List<string> as it supports LINQ: XmlNodeList skillNameNodeList=SkillXML.GetElementsByTagName("name"); List<string> skills = new List<string>(); foreach (XmlNode skillNameNode in skillNameNodeList) { skills.Add(skillNameNode.Attributes["value"].Value); } ...

    HTML CSS Two 2-column tables side by side with same height and width

    html,css

    Okay so I have made a few assumptions to create this solution. Firstly, I'm guessing that as you are setting the headers of the tables as width:200px; that the width of the two columns are 100px. (This can be changed if need be). Secondly, these tables are not floated. This...

    Difference between application and module pipelines in Nancy?

    c#,asp.net,nancy

    The module- and application pipelines are explained in detail in the wiki. It's basically hooks which are executed before and after route execution on a global (application pipelines) and per-module basis. Here's an example: If a route is resolved to a module called FooModule, the pipelines will be invoked as...

    Top header 100% of screen, but body only 70%?

    html,css

    Put your header inside the body. And don't apply styles to the body but use a container. + You should have one single header in your page. <body> <header> <nav><ul> <li class="active"><a href="#">Home</a></li> <li><a href="#">Solutions & Services</a> <ul> <li><a href="#">Internet</a></li> <li><a href="#">Networking</a></li> <li><a href="#">Website</a></li> <li><a href="#">Home...

    How to set DIV's width based on CSS indexes

    html,css

    If I understand this correctly,all you need to do is change your CSS to the following: .sintesi-offerta > .block:nth-child(3n+1) { width: 40%; } .sintesi-offerta > .block:nth-child(3n+2) { width: 20%; } .sintesi-offerta > .block:nth-child(3n+3) { width: 40%; } Side note: your br tags should be <br/> for jsfiddle to interpret them...

    Why is the task is not cancelled when I call CancellationTokenSource's Cancel method in async method?

    c#,asynchronous,task,cancellationtokensource,cancellation-token

    Cancellation in .Net is cooperative. That means that the one holding the CancellationTokenSource signals cancellation and the one holding the CancellationToken needs to check whether cancellation was signaled (either by polling the CancellationToken or by registering a delegate to run when it is signaled). In your Task.Run you use the...

    Validate a field only if it is populated

    c#,wpf,idataerrorinfo

    You can implement your OptionalPhoneAttribute based on the original PhoneAttribute: public sealed class OptionalPhoneAttribute : ValidationAttribute { public override bool IsValid(object value) { var phone = new PhoneAttribute(); //return true when the value is null or empty //return original IsValid value only when value is not null or empty return...

    Get object by attribute value [duplicate]

    c#,reflection,custom-attributes,spring.net

    If you have obtained the Assembly, you can just iterate over the types and check for your conditions: var matchingTypes = from t in asm.GetTypes() where !t.IsInterface && !t.IsAbstract where typeof(ICustomInterface).IsAssignableFrom(t) let foo = t.GetCustomAttribute<FooAttribute>() where foo != null && foo.Bar == Y select t; I am assuming you want...

    CSS - Linear Gradient Background Color no-repeat is not working for if it has multiple tds

    html,css,css3

    table{border-collapse:collapse;width:100%} table tr td{padding:5px;border:1px solid #000; background:#FFF } table tr:hover td{padding:5px;border:1px solid #000; background:transparent } table{ background:...

    Load XML to list using LINQ [duplicate]

    c#,xml,linq

    Make a base class which will have id,x,y,z, and have Vendors,Bankers and Hospitals extend it. Then you can have a collection of the base class, and add to it the classes that inherit from it....

    change css dynamically by selecting dropdown list item

    jquery,html,css,drop-down-menu

    I have created a working example for you. You can find the jsfiddle in here This piece of code uses JQuery. (Remember, for these type of tasks, JQuery is your friend =] ). HTML <select id="dropDownMenu"> <option value="option1" selected="selected">yes</option> <option value="option2">no</option> </select> <br> <img id="picture" src="https://upload.wikimedia.org/wikipedia/commons/thumb/f/f5/House_Sparrow_mar08.jpg/220px-House_Sparrow_mar08.jpg"> Javascript function changeStyle(){...

    Centering navbar pills vertically within the navbar using flexbox

    html,css,twitter-bootstrap,flexbox

    Set display: flex for the <ul class="nav">, not for items. Also use align-items: center for vertical aligment: .nav { height: 70px; display: flex; justify-content: center; align-items: center; } <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet"/> <div class="container"> <nav class="navbar navbar-default navbar-fixed-top"> <ul id="nav_pills" class="nav nav-pills" role="tablist"> <li role="presentation"> <a href="/">About</a> </li> <li...

    Index was out of range. Must be non-negative or less than size of collection [duplicate]

    c#

    It looks like you have a typo in your loop condition: for (int index = filePaths.Count(); filePaths.Count() > 9; index--) It should be for (int index = filePaths.Count() - 1; index > 9; index--) Also note that for the first iteration of loop you're trying to access filePaths[filePaths.Count()] which is...

    How to declare var datatype in public scope in c#?

    c#,linq

    Declare it as a known type (not an anonymous type), like this for example: Dictionary<int, string> results = new Dictionary<int, string>(); Then you could store the results in the Dictionary: results = behzad.GAPERTitles.ToDictionary(x => x.id, x => x.gaptitle); And reference it later: private void button1_Click(object sender, EventArgs e) { //...

    Detect when the jQuery UI slider is being moved?

    jquery,html,css,jquery-ui

    You can use 3-Events: - Start (Start-Sliding) -> Stop Player - End (End-Sliding) -> Start Player - Slide (Sliding) -> Move Player-Position $("#range").slider({ range: "min", start: function(event, ui) { player.pauseVideo(); }, stop: function(event, ui) { player.playVideo(); }, slide: function(event, ui) { player.seekTo(ui.value,true); return false; } }); Demo: http://codepen.io/anon/pen/EjwMGV...

    How can I determine if an object of anonymous type is empty?

    c#,.net

    Anonymous types do not provide operator overloads for ==, although it wouldn't matter in this case since one of the arguments is typed object. However the C# compiler does provide Equals, GetHashCode, and ToString implementations. Use the static object.Equals, method which will do the appropriate null checks and then call...

    bootstrap - dynamically changing jumbotron background image

    javascript,jquery,html,css,bootstrap

    You have some syntax errors otherwise everything is good!! keep url inside quotes as below: $('.jumbotron').css('background-image','url(/path/to/new/image)'); ...

    Memory consumption when chaining string methods

    c#,string,immutability,method-chaining

    Is it true that when you chain string functions, every function instantiates a new string? In general, yes. Every function that returns a modified string does so by creating a new string object that contains the full new string which is stored separately from the original string. There are...

    How to Customize Visual Studio Setup

    c#,visual-studio,setup-project

    You can use a Microsoft Setup project or WIX (easily integrate with Visual Studio). Both are free. •You can do almost all of your customization in setup project by adding custom actions. •WIX (window installer xml) is the better option. You can do a complete customization from wix but it...

    Regex to remove `.` from a sub-string enclosed in square brackets

    c#,.net,regex,string,replace

    To remove all the dots present inside the square brackets. Regex.Replace(str, @"\.(?=[^\[\]]*\])", ""); DEMO To remove dot or ?. Regex.Replace(str, @"[.?](?=[^\[\]]*\])", ""); ...

    show div only when printing

    javascript,html,css

    You need some css for that #printOnly { display : none; } @media print { #printOnly { display : block; } } ...

    Foreign key in C#

    c#,sql,sql-server,database

    You want create relationship in two table Refer this link http://www.c-sharpcorner.com/Blogs/5608/create-a-relationship-between-two-dataset-tables.aspx...

    Catch concurrency exception in EF6 to change message to be more user friendly

    c#,asp.net,.net,entity-framework,entity-framework-6

    You are executing an asynchronous method. This means that any exceptions will be thrown when you call await on the returned task or when you try to retrieve the results using await myTask; You never do so, which means that the exception is thrown and caught higher up your call...

    SQL Server / C# : Filter for System.Date - results only entries at 00:00:00

    c#,asp.net,sql-server,date,gridview-sorting

    What happens if you change all of the filters to use 'LIKE': if (DropDownList1.SelectedValue.ToString().Equals("Start")) { FilterExpression = string.Format("Start LIKE '{0}%'", TextBox1.Text); } Then, you're not matching against an exact date (at midnight), but matching any date-times which start with that date. Update Or perhaps you could try this... if (DropDownList1.SelectedValue.ToString().Equals("Start"))...

    C# XML: System.InvalidOperationException

    c#,xml

    Is "User Info" and "Course Data" is a different entity. If it is so, I think you may encapsulate them in one entity. XmlTextWriter writer = new XmlTextWriter(path, System.Text.Encoding.UTF8); writer.WriteStartDocument(true); writer.Formatting = Formatting.Indented; writer.Indentation = 4; writer.WriteStartElement("My Entity"); /* It is a biggest one*/ writer.WriteStartElement("User Info"); writer.WriteStartElement("Name"); writer.WriteString(userName); writer.WriteEndElement(); writer.WriteStartElement("Tutor...

    How to make background body overlay when use twitter-bootstrap popover?

    html,css,twitter-bootstrap

    Posting some more code would be nice. This should work. Use some jQuery or AngularJs or any other framework to make the .overlay initially hidden, then to make it visible when needed. If you need help, comment. If it helps, +1. EDIT $(function() { $('[data-toggle="popover"]').popover({ placement: 'bottom' }); $("#buttonright").click(function() {...

    Is it possible to concactenate a DataBound value with a constant string in XAML DataBinding?

    c#,xaml,windows-phone

    You can use a StringFormat in your binding, like so: <TextBox Text="{Binding ItemName, StringFormat={}Item: {0}}"/> That being said, it may cause some unexpected behavior when editing. For example, if the user edits only the item name (excluding the 'Item:' text), then when the TextBox loses focus, the string format will...

    C# PCL HMACSHAX with BouncyCastle-PCL

    c#,bouncycastle,portable-class-library

    Try like this for HmacSha256 public class HmacSha256 { private readonly HMac _hmac; public HmacSha256(byte[] key) { _hmac = new HMac(new Sha256Digest()); _hmac.Init(new KeyParameter(key)); } public byte[] ComputeHash(byte[] value) { if (value == null) throw new ArgumentNullException("value"); byte[] resBuf = new byte[_hmac.GetMacSize()]; _hmac.BlockUpdate(value, 0, value.Length); _hmac.DoFinal(resBuf, 0); return resBuf; }...