开发者

Not display/write specific html if model.entity is null

开发者 https://www.devze.com 2023-01-04 18:27 出处:网络
Normally I work in ASP Classic, and am still a bit green on ASP.Net MVC. I have my model with its fields or entities (might not be the right word hence why not able to find 开发者_StackOverflow社区if

Normally I work in ASP Classic, and am still a bit green on ASP.Net MVC.

I have my model with its fields or entities (might not be the right word hence why not able to find 开发者_StackOverflow社区if previously answered, forgive me), and some of these will have null values such as hyperlinks, email address, specific types of phone numbers, etc.

What I want to do is not write certain blocks of HTML within the foreach loop if a field is empty.

In ASP Classic, I would have written an If statement along the lines of:

<% If RS.field <> NULL then %>HTML with <%=RS.field %><% End If %>
<% If RS.field2 <> NULL then %>HTML with <%=RS.field2 %><% End If %>
...

However, I don't know how to achieve the same result in ASP.Net MVC.

In one of my current usages, a list of sellers returned for a specific set of search results, it runs through a foreach loop and returns the current HTML (in part):

Website: <a class="url" href="<%= seller.ContactWebsite %>" target="_blank" title="Visit the website for  <%= seller.Name %>"><%= seller.ContactWebsite %></a><br />

So, if for example I have a field from the model, say seller.ContactWebsite, and this field was NULL, I would not want it to write this as part of the foreach loop.

All answers and assistance appreciated.


If you are using the WebForms view engine with C# here's how your code might look like:

<% if (!string.IsNullOrEmpty(Model.field1)) { %>
    HTML with <%= Model.field1 %>
<% } %>

This assumes that your view is strongly typed to a model class and that the controller action provided to the view an instance of this model.

As you can see this syntax turns quickly into a tag soup as mixing markup with server side code is ugly. To solve this you could write a custom HTML helper method that will be responsible for properly formatting.

Let's take for example this snippet:

<a class="url" href="<%= seller.ContactWebsite %>" target="_blank" title="Visit the website for  <%= seller.Name %>"><%= seller.ContactWebsite %></a>

Here's how a potential helper method might look like:

public static MvcHtmlString MyCustomLink(this HtmlHelper htmlHelper, SellerViewModel seller)
{
    if (seller == null)
    {
        return MvcHtmlString.Empty;
    }
    var anchor = new TagBuilder("a");
    anchor.AddCssClass("url");
    anchor.MergeAttribute("href", seller.ContactWebsite);
    anchor.MergeAttribute("target", "_blank");
    anchor.MergeAttribute("title", "Visit the website for " + seller.Name);
    anchor.SetInnerText(seller.ContactWebsite);
    return MvcHtmlString.Create(anchor.ToString());
}

which could be used like this in the for loop:

<%= Html.MyCustomLink(seller) %>
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号