开发者

How do I render a multiple-model CREATE form on the fly?

It's a multi-model view, and I'm achieving this through an IList<Book>. Each Book has a Title and an Author

So for example if I wanted to make 3 Books:

<%= Html.TextBoxFor(m => m[0].Title) %>
<%= Html.TextBoxFor(m => m[0].Author) %>

<%= Html.TextBoxFor(m => m[1].Title) %>
<%= Html.TextBoxFor(m => m[1].Author) %>

<%= Html.TextBoxFor(m => m[2].Title) %>
<%= Html.TextBoxFor(m => m[2].Author) %>

and so forth.

However, I want to be able to generate such a form for any number of Books. I've done this before in Ruby on Rails through JavaScript and rendering partials, but I don't think I can render a partial in this case because the form changes (the index of the book has to increment for it to work)

EDIT: I'm looking for a way to do this in the Create view in particular. So in this case I don't have a list of books, but I'm building it.

A user should be able to click on a link that says "Add another item" and a fo开发者_JAVA百科rm for another book should be appended to the bottom.

Any ideas? Some sample code would be extremely helpful (I'm very new to ASP.NET)!


Editor templates are a great way to achieve this:

Model:

public class Book
{
    public string Title { get; set; }
    public string Author { get; set; }
}

Controller:

public ActionResult Index()
{
    // Fetch the books from your repository:
    var books = new[]
    {
        new Book { Title = "title 1", Author = "author 1" },
        new Book { Title = "title 2", Author = "author 2" },
    };
    return View(books);
}

View ~/Views/Home/Index.aspx (strongly typed to IEnumerable<Book>):

<%= Html.EditorForModel() %>

Editor template ~/Views/Shared/EditorTemplates/Book.ascx (strongly typed to Book):

<%= Html.TextBoxFor(x => x.Title) %>
<%= Html.TextBoxFor(x => x.Author) %>


Something like this should do it:

<%
foreach (var book in Model)
{
    %>
    <p>Title: <%= Html.TextBoxFor(book.Title) %></p>
    <p>Author: <%= Html.TextBoxFor(book.Author) %></p>
    <%
}
%>

You can use most C# code within a view, inside <% %> blocks.


Send a list to the view and loop through using foreach.
http://weblogs.asp.net/scottgu/archive/2007/12/06/asp-net-mvc-framework-part-3-passing-viewdata-from-controllers-to-views.aspx

EDIT:

I answered a similar question yesterday. This is Web Forms but it should work in MVC as well

Programmatically add controls to form

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜