Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • Simon 4 posts 95 karma points
    Feb 20, 2018 @ 14:59
    Simon
    1

    HasProperty and HasValue checking strongly typed models

    Hi,

    I am using the ModelsBuilder and using strongly typed syntax in my Views.

    I want to know the Strongly typed equivalent/best practice to using HasValue/HasProperty is.

    For a string property named 'projectTitle', I have used the following

    @if (!string.IsNullOrEmpty(Model.ProjectTitle))
    {
       <h2>@Model.ProjectTitle</h2>
    }
    

    But I am struggling trying to do similar for a Multinode Tree picker property named 'projectItems' as that returns a IEnumerable .

    I have ended up using this, which works, but this defeats object of using strongly typed

    @if (Model.HasValue("projectItems"))
    {
        //do something
    }
    

    What is best practice in this situation?

    Thanks Simon

  • Dan Diplo 1505 posts 5911 karma points MVP 4x c-trib
    Feb 20, 2018 @ 15:23
    Dan Diplo
    102

    If Model.ProjectItems is of type IEnumerable then you can do:

    if (Model.ProjectItems != null && Model.ProjectItems.Any())
    {
       // do something
    }
    

    So basically you check it's not NULL and then you check if the sequence contains any items. The Any() method is an extension method within System.Linq namespace.

  • Simon 4 posts 95 karma points
    Feb 20, 2018 @ 15:40
    Simon
    0

    Thanks Dan - that worked perfectly

  • This forum is in read-only mode while we transition to the new forum.

    You can continue this topic on the new forum by tapping the "Continue discussion" link below.

Please Sign in or register to post replies