Binding a List to a Table

Anjali Agarwal 1,571 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

Developer technologies | ASP.NET | ASP.NET Core
Developer technologies | ASP.NET | Other
Developer technologies | C#
Developer technologies | 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.
0 comments No comments
{count} votes

Answer accepted by question author
  1. Anonymous
    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

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.