简体   繁体   中英

How do I change the font color of a specific text bound to a model on a Razor page?

I am building an ASP.NET Core web application and would like to style certain text in my result table a different color than the rest of the table. For example:

期望的结果

I am trying to do this in JavaScript but seem to be running into issues because the data is generated on the page from the model after a Search button is clicked with the selected parameters. Here is what I have in my HTML Razor page:

@foreach (var item in Model.SecurityLog)
{
  <tr>
  <td style="width:7% !important" id="eventType">
      @Html.DisplayFor(modelItem => item.EventType.Name)
  </td>
  <td style="width:9% !important">
      @Html.DisplayFor(modelItem => item.ContactName)
  </td>
}

Here is the JavaScript code that is also on the Razor page:

 var text = document.getElementById("searchString");
 var str = text.innerHTML;
 var reg = /RL Solution Required/ig;

 var toStr = String(reg);
 var search = (toStr.replace('\/g', '|')).substring(1);
 var searches = search.split("|");

 if (searches.indexOf("RL Solution Required") > -1) {
    str = str.replace(/RL Solution Required/g, '<span style="color:red;">R/L Solution Required</span>');
 }
 document.getElementById("searchString").innerHTML = str;

I am trying to get the RL Solution Required font to be in red. I am not experiencing any errors with this code but the font is black. Thanks in advance and any help is appreciated.

You don't need to use Javascript for this. Just use Razor.

@foreach (var item in Model.SecurityLog)
{
  <tr>
  <td style="width:7% !important">        
      @{
        string eventType = item.EventType.Name;
      }
      @if(eventType.Contains("RL Solution Required"){
        <span style="color:red;">@Html.DisplayFor(modelItem => eventType)</span>
      }else{
        @Html.DisplayFor(modelItem => eventType)
      }          
  </td>
  <td style="width:9% !important">
      @Html.DisplayFor(modelItem => item.ContactName)
  </td>
}

The issue you're experiencing could be for a number of reasons.

For example: I see you using.important in some of your css, If you have another span tag with a color property that also is set to.important, it will be overriding the color that you are inserting into your html.

The best thing to do would be to inspect the element in a browser's dev tools and try modifying the css to properly update the color there. If you can get it to update there and describe what you have changed, it will be easier to narrow down the specific issue that you are having here.

If you ARE able to modify the element properly using css and something needs changed in your generated code, you may be able to just go from there and figure it out.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM