Copied to clipboard

Flag this post as spam?

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


  • dev-thandabantu 41 posts 321 karma points
    Mar 16, 2023 @ 05:41
    dev-thandabantu
    0

    How to use the @Model?

    I have "test" variable that has the following properties: test variable

    Can someone please explain to me why test.Title gives this error: fail error

    Here is the full code snippet:

    @foreach (var category in Model.CategoryBlocks)
        {
            <div class="col-lg-4 col-md-6 mb-4">
                <div class="card h-100">
                    <div class="card-body">
                        @{
                            var test = @category.Content;
                            //var d = test.Title;
                            var c = 0;
                        }
                        <h2 class="card-title">@category.Content</h2>
                        <p class="card-text">@*@category.CategoryBlurb*@</p>
                        <a href="#" class="btn btn-primary">Show More</a>
                    </div>
                </div>
            </div>
        }
    
  • Dennis 75 posts 398 karma points MVP 2x
    Mar 16, 2023 @ 06:11
    Dennis
    1

    Hi there!

    I know why you cannot access the title property. The return type of @category.Content is IPublishedElement. Like the error says: This type does not have a property 'Title'. You have to explicitly tell the compiler that this is a CategoryBlock. You can do that with a type cast

  • Yari Mariën 5 posts 99 karma points c-trib
    Mar 16, 2023 @ 12:26
    Yari Mariƫn
    101

    Cast type or use the .Value method.

    @foreach (var category in Model.CategoryBlocks)
    {
        <div class="col-lg-4 col-md-6 mb-4">
            <div class="card h-100">
                <div class="card-body">
                    @{
                        var test = @category.Content;
    
                        //Solution 1 (type cast from IPublishedContent to CategoryBlock)
                        //var d = ((CategoryBlock)test).Title;
    
                        //Solution 2 (use the Value method)
                        //var d = test.Value("title");
    
                        var c = 0;
                    }
                    <h2 class="card-title">@category.Content</h2>
                    <p class="card-text">@*@category.CategoryBlurb*@</p>
                    <a href="#" class="btn btn-primary">Show More</a>
                </div>
            </div>
        </div>
    }
    
Please Sign in or register to post replies

Write your reply to:

Draft