asp.net-mvc 如何使用绑定前缀?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1317523/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use Bind Prefix?
提问by chobo2
Say if I had this table in my db: Product
假设我的数据库中有这个表:产品
It had
它有过
ProductId
ProductName
ProductType
Now for whatever reason I can't name my textboxes ProductName and ProductType so now my View Method would look like this
现在无论出于何种原因我都无法命名我的文本框 ProductName 和 ProductType 所以现在我的视图方法看起来像这样
public ViewResult Test([Bind(Exclude ="ProductId")] Product)
So now through my playing around nothing would be matched in this product since they have different names.
所以现在通过我的尝试,这个产品中没有任何东西可以匹配,因为它们有不同的名称。
So I guess this is where Prefix would come in but I don't know how to use it. Nor how do I use it and Exclude at the same time.
所以我想这是 Prefix 的用武之地,但我不知道如何使用它。也不如何同时使用它和排除。
Can someone give me an example?
有人可以举个例子吗?
回答by John Foster
The prefix is used as follows if in your view you have...
如果在您看来您有...
<select name="p.ProductType">....</select>
<input type="text" name="p.ProductName" />
You can bind the incoming form to an instance of your model by doing something like
您可以通过执行以下操作将传入表单绑定到模型的实例
public ActionResult([Bind(Prefix="p")]Product product)
You should note that MVC would do this automatically for you if you named your method argument p.
您应该注意,如果您将方法参数命名为 p,MVC 会自动为您执行此操作。
The prefix can be very useful if you're trying to bind multiple entities at the same time (e.g. two name fields).
如果您尝试同时绑定多个实体(例如两个名称字段),前缀可能非常有用。
To use the exclude binding to certain Properties (i.e. avoid people passing in ProductIds in a forged form) just set the property names to exclude
要对某些属性使用排除绑定(即避免人们以伪造的形式传入 ProductId),只需将属性名称设置为 exclude
public ActionResult([Bind(Prefix="p", Exclude="ProductId")]Product product)
This will ensure that the ProductId on your entity never gets set.
这将确保您的实体上的 ProductId 永远不会被设置。
If you want to bind two completely different field names e.g. Type to ProductType you can look at custom model binding or just grabbing the field out the FormCollection yourself.
如果您想绑定两个完全不同的字段名称,例如 Type 到 ProductType,您可以查看自定义模型绑定或自己从 FormCollection 中获取该字段。

