How to expose a collection of items from MVC model

2019-08-21 05:21发布

问题:

I have a MVC model oject that contains a collection of object. I want to expose the MVC model as user input fields on a MVC view.

Below is MVC model and domain model

 public class BookModel
    {
        public BookModel(Book book)
        {
            this.Authors = book.Authors;
        }   

        public List<Author> Authors { get; set; }
    }

    public  class Book
    {
        public List<Author> Authors = new List<Author>();
    }

    public class Author
    {
        public string Name { get; set; }
    }

Below is the Action method in controller:

public ActionResult Edit(int id)
        {

            BookModel model = GetBookModel(id);
            return View(model);
        }

The problem is that, the generated view (*.cshtml) does NOT have the input fields for the collection authors.

Any idea would be very much appreciated.

回答1:

The problem is that, the generated view (*.cshtml) does NOT have the input fields for the collection authors.

The ASP.NET MVC new View wizard does its best. From there its up to you.

So inside Edit.cshtml you could use editor templates:

@model BookModel

@using (Html.BeginForm())
{
    <table>
        <thead>
            <tr>
                <th>Name</th>
                <th>Text</th>
            </tr>
        </thead>
        <tbody>
            @Html.EditorFor(x => x.Authors)
        </tbody>
    </table>

    <input type="submit" value="Edit" />
}

and then define a editor template for an Author (~/Views/Shared/EditorTemplates/Author.cshtml) which will be rendered automatically for each element of your collection:

@model Author
<tr>
    <td>@Html.EditorFor(x => x.Name)</td>
    <td>@Html.EditorFor(x => x.Text)</td>
</tr>