Multiple partial views based on same model

2019-08-23 01:53发布

问题:

I have something like this:

Main view:

@model AuthorViewModel
@using (Html.BeginForm("Action", "Controller", FormMethod.Post, new { id="someId"        })) {

 @Html.LabelFor(model => model.Name);
 @Html.EditorFor(model => model.Name);
 @Html.ValidationMessageFor(model => model.Name);

 <label> Book </label>
 @{Html.RenderPartial("_BookView", new BookViewModel());}
 <label>One more book...</label>
 @{Html.RenderPartial("_BookView", new BookViewModel());}
}

Partial view:

@model BookViewModel
@Html.LabelFor(model => model.Title);
@Html.EditorFor(model => model.Title);
@Html.ValidationMessageFor(model => model.Title);

AuthorViewModel:

public class AuthorViewModel
{
    [Required]
    [DataType(DataType.Text)]
    public String Name { get; set; }
}

BookViewModel:

public class BookViewModel
{
    [Required]
    [DataType(DataType.Text)]
    public String Title { get; set; }
}

So when it renders - it looks right, but validation is the same for all books. An I need to have a lot of books(say to add them dynamically) for author and each one have to be independent and "validatable".

How can I perform such behaviour?

回答1:

I would have a collection of BookViewModel in your AuthorViewModel. That way the names and ids will be unique.



回答2:

You could update your AuthorViewModel to have a List of BookViewModel. In the View, iterate over the list and create the necessary fields for the booktitles.



回答3:

You're trying to model bind to a list. Its pretty simple to implement, have a look at Phil Haacks post here. He uses the old mvc views, but the same idea works fine for razor