Binding a List to a Table

Anjali Agarwal 1,386 Reputation points
2023-05-10T02:11:08.0766667+00:00

I have the following controller:

  public async Task<IActionResult> Display(SelfServiceTransaction trans)
        {
            Transactions transactions = new Transactions(_recorderContext); 
            List<Author> author = transactions.getAuthors(trans.Id);
            return View();
        }

Below is the list of Author that I am returning from the class:

list of objects:

// Create a List of objects

public List<Author> getAuthors(string id)

{

List<Author> authors = new List<Author>

{

new Author { Name = "Test1", Book = "Apress1", Price = 49.95 },

new Author { Name = "Test2", Book = "Apress2", Price = 19.95 },

new Author { Name = "Test3", Book = "Press3", Price = 29.95 }

};

return authors;

}

I want to create a table in my view that shows all the list of Authors so something like this:

User's image

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,404 questions
ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,419 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,651 questions
0 comments No comments
{count} votes

Accepted answer
  1. Jerry Fu - MSFT 576 Reputation points Microsoft Vendor
    2023-05-10T12:38:46.15+00:00

    Hi,you can try the following code. Assume you get the 'author' value in the Controller.

            public async Task<IActionResult> Display()
            {
                var author = new List<Author>
                {
                    new Author { Name = "Test1", Book = "Apress1", Price = 49.95 },
                    new Author { Name = "Test2", Book = "Apress2", Price = 19.95 },
                    new Author { Name = "Test3", Book = "Press3", Price = 29.95 }
                };
    
                return View(author);
            }
    

    And the Display.cshtml

    @model List<Author>
    
    <table class="table table-bordered table-responsive table-hover">
        <tr>
            <th>Name </th>
            <th>Book </th>
            <th>Price </th>
        </tr>
        @foreach (var d in Model)
        {
            <tr>
                <td>@d.Name</td>
                <td>@d.Book</td>
                <td>@d.Price</td>
            </tr>
        }
    </table>
    

    The output

    User's image


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment". Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful