if an object does not have the value - do not display [duplicate] - asp.net-mvc

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 7 years ago.
I try to do something like that. When my employee does not have a particular value that it is not displayed. I tried to do it like this:
#foreach (var item in Model)
{
if (!item.Przewodnik.Uprawnienia.IsNullOrWhiteSpace()) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.Przewodnik.Pracownik.Osoba.Imie)
</td>
(...)
But it give me a .NullReferenceException.
if(item.Przewodnik.Uprawnienia != null){...}
I tried this as well, but also give error.

Try the following:
#foreach (var item in Model)
{
if (item != null && item.Przewodnik != null && !string.IsNullOrEmpty(item.Przewodnik.Uprawnienia)) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.Przewodnik.Pracownik.Osoba.Imie)
</td>
(...)

Related

Nested foreach loop in ASP.NET MVC

I have problem with my nested foreach. As you see in the screenshot, it just returns all data in every dt.
I know how to solve my problem with a partial view. But I just want to know is there solution with foreach or some other loop.
public class VM
{
public IEnumerable<x> Upi { get; set; }
public IEnumerable<y> Adre { get; set; }
}
View
#foreach (var item in Model.Upi)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.Surname)
</td>
<td>
#foreach (var smece in Model.Adre)
{
<div>
<pre>
#Html.DisplayFor(modelItem => smece.Ul)
#Html.DisplayFor(modelItem => smece.Ku), #Html.DisplayFor(modelItem => smece.Gr)
</pre>
</div>
}
</td>
Sorry guys I am stupid. It was simple. I just had to put one if.
if (smece.AU_ID == item.AU_ID) before pre and it works. TY all. Now only problem is, is there maybe other way where it doesnt need to iterate whole foreach and just go to direct AU_ID.

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>
}

Writing conditional HTML with razor

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)

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>
}

How does one avoid a NullReferenceException in a foreach loop within a View when my model is null?

I get a "NullReferenceException was unhandled by user code" error with the following code in my View when I pass in a null value via my controller. There are situations where I want to pass in a null value, but I do not want an error thrown when this happens. What should I change my code to?
Originally my code was:
#foreach (var item in Model.MyModelStuff)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Bla.Title)
</td>
<tr>
}
I have tried the following with no success:
#foreach (var item in Model.MyModelStuff.Where( item => item.MyModelStuff != null))
etc. . .
How do I change the code so that it will handle null without throwing an error? I've read I may need to be returning an empty collection of my model (?), how would I go about doing that - if it is indeed the necessary thing to do?
If my understanding is correct your collection is null.
A collection should never be null, like you said you should return an empty collection instead and prevent your collection to be corrupted not exposing the real collection:
public IList<Employee> Employees
{
get;
private set;
}
And initialize your collection inside the constructor
this.Employees = new List<Employee>();
Honestly, I think a null model is a poor choice. But if you insist, just add an if check:
#if (Model != null) {
foreach (var item in Model.MyModelStuff)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Bla.Title)
</td>
<tr>
}
}

Resources