Writing conditional HTML with razor - asp.net-mvc

Depending on my record, I'd like to change the style of the table row in my current iteration.
The below example doesn't work, but how would I go about doing this correctly?
foreach (var item in Model)
{
#{
if (item.DataState != DataState.Active)
{
<tr style="background-color: red">
}
else
<tr>
}
<td>#item.Name</td>
</tr>
}
So effectively, I'd like to dynamically render the <tr> element differently based on the DataState of my model.

Here's a shorter approach:
#foreach (var item in Model)
{
<tr #(item.DataState != DataState.Active ? "style=background-color:red" : "")>
<td>#item.Name</td>
</tr>
}
Edit: Code fixed

There are multiple way you can write condition.
Option 1:
#foreach (var item in Model)
{
if (item.DataState != DataState.Active)
{
<tr style="background-color: red">
<td>#item.Name</td>
</tr>
}
else
{
<tr>
<td>#item.Name</td>
</tr>
}
}
Option 2:
#foreach (var item in Model)
{
<tr style="#( item.DataState != DataState.Active ? "background-color: red;" : "" )">
<td>#item.Name</td>
</tr>
}

Define the attributes in a variable. The razor parser will omit the attribute if its value is null
#foreach (var item in Model)
{
var attributes = item.DataState == DataState.Active ? null : "background-color: red";
<tr style=#attributes>
<td>#item.Name</td>
</tr>
}

Not sure what kind of error you faces right now, but i gess your problem is that Razor don't understand all cases of tricky html render.
You can force him to render html where you need with #: symbol for single string or <text> tag like this:
#foreach (var item in Model)
{
if (item.DataState != DataState.Active)
{
#: <tr style="background-color: red">
}
else
{
<text><tr></text>
}
<td>#item.Name</td>
</tr>
}

You're probably going to get compile errors if you start splitting the <tr> tag up in the view and I'd not duplicate large chunks of code. I would do the following:
#foreach(var item in Model) {
string strStyle=String.Empty;
if(item.DataState!=DataState.Active) { strStyle = "background-color:red;" }
<text>
<tr style="#strStyle">
<td>#item.Name</td>
</tr>
</text>
}

#(item.DataState != DataState.Active ? "style=" + "background-color:red" : "")

#(!string.IsNullOrWhiteSpace(Model?.District?.Name) ? Html.Raw($"<span class=\"location\">{Model?.District?.Name}</span>") : string.Empty)

Related

printing static message inside foreach loop

I am trying to print static message in the foreach loop section, but not getting any display message.
#foreach (var item in Model) {
<tr>
<td>
#*#Html.DisplayFor(modelItem => item.Status)*#
#if (item.Status == 1)
{
#Html.Display("active")
}
else if (item.Status == 2)
{
#Html.Display("inactive")
}
</td>
</tr>
}
Instead of printing the Status value, I am trying to print as above. But under the Status column I am not getting any message.
You can use #Html.Raw or special Razor tag <text>.
Here is a sample how to use them:
<td>
#*#Html.DisplayFor(modelItem => item.Status)*#
#if (item.Status == 1)
{
#Html.Raw("active")
}
else if (item.Status == 2)
{
<text>inactive</text>
}
</td>
I am assuming the Status is an integer
Do this instead:
#foreach (var item in Model) {
<tr>
<td>
#if (item.Status == 1)
{
<span>Active</span>
}
else
{
<span>InActive</span>
}
</td>
</tr>
}

Cannot convert type 'char' to 'string

I am getting this error in one project and the code works perfectly fine on another project. I have tried multiple to duplicate the code as it is. Is there a way to find where the error originated from??
#if (ViewBag.RolesForThisUser != null)
{
<div style="background-color:lawngreen;">
<table class="table">
<tr>
<th>
#Html.DisplayName("Roles For This User")
</th>
</tr>
<tr>
<td>
#foreach (string s in ViewBag.RolesForThisUser) //this line
{
<li>#s</li>
}
</td>
</tr>
</table>
I suspected ViewBag.RolesForThisUser itself already contains a string, neither an array nor collection of strings (e.g. string[] or List<string>), hence using foreach loop is pointless (and string itself contains char[] array which explains why type conversion failed). You can simply display it without foreach:
#if (!string.IsNullOrEmpty(ViewBag.RolesForThisUser))
{
<div style="background-color:lawngreen;">
<table class="table">
<tr>
<th>
#Html.DisplayName("Roles For This User")
</th>
</tr>
<tr>
<td>
#ViewBag.RolesForThisUser
</td>
</tr>
</table>
</div>
}
Or assign a string collection to ViewBag.RolesForThisUser from GET method so that you can use foreach loop, like example below:
Controller
public ActionResult ActionName()
{
var list = new List<string>();
list.Add("Administrator");
// add other values here
ViewBag.RolesForThisUser = list;
return View();
}
View
#if (ViewBag.RolesForThisUser != null)
{
<div style="background-color:lawngreen;">
<table class="table">
<tr>
<th>
#Html.DisplayName("Roles For This User")
</th>
</tr>
<tr>
<td>
#foreach (string s in ViewBag.RolesForThisUser)
{
<p>#s</p>
}
</td>
</tr>
</table>
</div>
}

MVC For..Each how to set class conditionally? [duplicate]

This question already has answers here:
Conditionally change CSS class in Razor view
(4 answers)
Closed 5 years ago.
I have a For...Each loop of a list in an MVC View. What I need to do is look at a property to determine if the records has been marked as deleted and then I would set the Bootstrap class of "danger" on a table row.
I can do a look at the property and write our the table row for each condition but that seems like extra work. If I use the following code Razor doesn't like the fact that it can't see the initial tag. Any suggestions on how to cleanly accomplish this?
#foreach (var item in Model.MyList)
{
if (item.IsDeleted == 1)
{
#Html.Raw("<tr class='danger'>")
}
else
{
#Html.Raw("<tr>")
}
<td>#item.FirstName</td>
<td>#item.LastName</td>
<td>#item.EmployeeId</td>
</tr>
}
Here is the simpler way for your problem
#foreach (var item in Model.MyList)
{
<tr class="#(item.IsDeleted ? "danger" : string.Empty) ">
<td>#item.FirstName</td>
<td>#item.LastName</td>
<td>#item.EmployeeId</td>
</tr>
}
How about something like this?
#foreach (var item in Model.MyList)
{
<tr class="#(Model.deleted ? "danger" : "")">
<td>#item.FirstName</td>
<td>#item.LastName</td>
<td>#item.EmployeeId</td>
</tr>
}
You can simply work with it this way
#foreach (var item in Model.MyList)
{
if (item.IsDeleted == 1)
{
<tr class="danger">
<td>#item.FirstName</td>
<td>#item.LastName</td>
<td>#item.EmployeeId</td>
</tr>
}
else
{
<tr>
<td>#item.FirstName</td>
<td>#item.LastName</td>
<td>#item.EmployeeId</td>
</tr>
}
or an alternative is
#foreach (var item in Model.MyList)
{
<tr #(item.IsDeleted != 1 ? String.Empty : "class=\"danger\"" )>
<td>#item.FirstName</td>
<td>#item.LastName</td>
<td>#item.EmployeeId</td>
</tr>
}

Replace string in Razor View

I would like to replace a string into Razor view and for some reason it does not work
#foreach (var item in Model)
{
<tr>
<td>#Html.DisplayFor(modelItem => item.User)</td>
<td>#Html.DisplayFor(modelItem => item.PasswordExpired.Replace("True", "Yes"))</td>
</tr>
}
Property PasswordExpired is a bool.
Any help would be appreciated.
It works nice with this code
#foreach (var item in Model)
{
<tr>
<td nowrap="">#Html.DisplayFor(modelItem => item.User)</td>
#{
if (item.PasswordExpired != null)
{
string isPasswordExpired = item.PasswordExpired.Replace("True", "Yes").Replace("False", "No");
<td>#isPasswordExpired</td>
}
else
{
string isPasswordExpired = "";
<td>#isPasswordExpired</td>
}
}
</tr>
}

MVC3 Razor - Formatting collection of strings

I have a collection of strings that are repeated in MVC3 Razor with the following code:
#if (Model.Publications != null)
{
<tr>
<th>Publications</th>
<td>
#foreach (var publication in #Model.Publications)
{
<text>#publication.Title</text>
}
</td>
</tr>
}
Now when I display this, all I get is:
Book1Book2Book3
But I really want is something like this:
Book1, Book2, Book3
Is there a simple way in MVC razor to achieve this without having to combine 'if' and 'foreach' statements?
#string.Join(",",Model.Publications.Select(p=>"<text>"+ p.Title+ "</text>"))
string.Join(", ", model.Publications.Select(pub => pub.Title).ToArray())
#if (Model.Publications != null)
{
<tr>
<th>Publications</th>
<td>
#var first = true
#foreach (var publication in #Model.Publications)
{
<text>#string.format("{0}{1}", first ? "" : ", ", publication.Title)</text>
#first = false;
}
</td>
</tr>
}

Resources