Multiple partial views based on same model

2019-08-23 02:18发布

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?

3条回答
2楼-- · 2019-08-23 02:24

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

查看更多
成全新的幸福
3楼-- · 2019-08-23 02:27

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.

查看更多
Fickle 薄情
4楼-- · 2019-08-23 02:41

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

查看更多
登录 后发表回答