【问题标题】:More complex(real-life) modelbinding?更复杂的(现实生活)模型绑定?
【发布时间】:2009-04-28 14:06:16
【问题描述】:

跟我一起来想象下面的例子:

Public ViewResult GiveMeFruit(int personId, string personName, int personAge, int fruitId){
    Person person = PersonService.GetPerson(personId);
    person.Name = personName;
    person.Age = age;
    person.Fruits.Add(FruitService.GetFruit(fruitId));
    ViewData.Person = person;
    View(ViewData);
}

这样应该做得更好

Public ViewResult GiveMeFruit(Person person, IFruit fruit){
    person.Fruits.Add(fruit);
    ViewData.Person = person;
    View(ViewData);
}

我之前尝试过正确的模型绑定,但无法使其正常工作。所有示例都向您展示了它如何与一种极其简单的类型一起工作,而不是多种复杂类型。 modelbinder 如何知道什么字段是什么类型的?如果有一个fruit1和一个fruit2怎么办?活页夹如何知道我的 IFruit 接口使用什么具体类型? 此外,我想知道如果我想给我的 Person 一个 IEnumerable 水果,它会如何工作。

【问题讨论】:

  • 我们不要去骆驼,这是一个愚蠢的地方。这只是一个模型..

标签: c# .net asp.net-mvc model-binding


【解决方案1】:

我相信它应该是这样的:

<input type="text" name="person.Name" value="" />
<input type="text" name="person.Age" value="" />
<input type="text" name="fruit.Property1" value="" />
<input type="text" name="fruit.Property2" value="" />

对于收藏:

<input type="text" name="fruit[0].Property1" value="" />
<input type="text" name="fruit[0].Property2" value="" />
<input type="text" name="fruit[1].Property1" value="" />
<input type="text" name="fruit[1].Property2" value="" />

喜欢this question

【讨论】:

  • 应该t parameters have Bind prefix in this case? Or its 只是我错过的另一个约定吗?
  • @Arnis L. 不,参数不必具有 Bind 前缀才能工作。看看这篇文章:hanselman.com/blog/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-18
  • 2021-02-05
  • 1970-01-01
  • 2016-03-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多