我有一个名为ArticleAdmin的视图模型,它包含一个复选框列表:
public class ArticleAdmin
{
public ArticleAdmin()
{
TopicCheckboxes = new List<TopicCheckbox>();
}
...
public IList<TopicCheckbox> TopicCheckboxes { get; set; }
...
}ToopicCheckbox有自己的viewmodel类,在一个单独的文件中定义:
public class TopicCheckbox
{
public bool IsAssociated { get; set; }
public string TopicName { get; set; }
public int TopicId { get; set; }
}这对于将模型传递到视图中非常有效:
(UPDATE:为了更清晰起见,这个操作方法是新包含的)
public ActionResult Edit(int id)
{
//Get the Article entity by id:
var articleEntity = Repository.Articles.Get<Article>(id);
//Map the entity to the viewmodel:
Mapper.CreateMap<Article, ArticleAdmin>();
// 2nd mapping to populate the article's relations to topics:
Mapper.CreateMap<TopicArticle, TopicArticleAdmin>();
var articleData = Mapper.Map<Article, ArticleAdmin>(articleEntity);
//Generate checkboxes (models) to manage associations with topics:
foreach (var topic in Repository.Topics.List())
{
var topicCheckbox = new TopicCheckbox { TopicId = topic.Id, TopicName = topic.Title };
if (Repository.TopicArticles.FindList(x => x.TopicId == topic.Id && x.ArticleId == id).Count() > 0)
topicCheckbox.IsAssociated = true;
//and add them to the viewmodel:
articleData.TopicCheckboxes.Add(topicCheckbox);
}
return View(articleData);
}...all我期望的复选框出现在表单中:
但很明显,这个列表并不是模型绑定回HttpPost“编辑”ActionMethod。
即使在表单中填充了TopicCheckboxes列表,ActionMethod中的列表仍然是空的。
[HttpPost]
public ActionResult Edit(ArticleAdmin articleData)..。articleData.TopicCheckboxes的计数为0。
那么,如何使模型绑定正常工作,以便正确填充回发ActionMethod中的复选框列表on回发。
发布于 2011-05-03 13:05:40
发布于 2011-05-04 11:14:14
好吧,我很大程度上是基于这个问题:用于复杂组合对象的自定义模型绑定器帮助
由于我现在觉得这可能是一个重复的问题,我将删除它,除非有人在第二天左右,并评论说,它是其他有用的。
关键是在复选框的输入名称属性中设置数组结构。在我的例子中,这意味着每个复选框都需要一系列隐藏的值:
<div>
<input type = "checkbox" name="TopicCheckboxes[1].IsAssociated" value = "true"id="topic_1" checked />
<input type = "hidden" name = "TopicCheckboxes.Index" value = "1" />
<input type = "hidden" name="TopicCheckboxes[1].IsAssociated" value = "false" />
<input type = "hidden" name = "TopicCheckboxes[1].TopicName" value = "test" />
<input type = "hidden" name = "TopicCheckboxes[1].TopicId" value = "1" />
<label for='topic_1'> test </label>
</div>真正非常重要的字段是第一个隐藏字段: TopicCheckboxes.Index“默认绑定器查看它自己使用的字段”,并且需要为每个复选框重复使用不同的值。
https://stackoverflow.com/questions/5869696
复制相似问题