基于同一模型的多个局部视图
我有这样的东西:
主视图:
@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());}
}
部分视图:
@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; }
}
所以当它呈现时 - 它看起来是正确的,但验证对于所有书籍都是相同的。我需要为作者提供很多书籍(比如动态添加它们),并且每一本书都必须是独立的且“可验证的”。
我怎样才能做出这样的行为?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我会在您的
AuthorViewModel
中收集BookViewModel
。这样名称和 ID 将是唯一的。I would have a collection of
BookViewModel
in yourAuthorViewModel
. That way the names and ids will be unique.您可以更新您的 AuthorViewModel 以拥有 BookViewModel 列表。在视图中,迭代列表并为书名创建必要的字段。
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.
您正在尝试对绑定到列表进行建模。
实现起来非常简单,请查看 Phil黑客在这里发帖。
他使用旧的 mvc 视图,但同样的想法也适用于 razor
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