如何使用绑定前缀? [英] How to use Bind Prefix?

查看:15
本文介绍了如何使用绑定前缀?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我的数据库中有这个表:产品

Say if I had this table in my db: Product

曾经

ProductId
ProductName
ProductType

现在无论什么原因我都不能命名我的文本框 ProductName 和 ProductType 所以现在我的视图方法看起来像这样

Now for whatever reason I can't name my textboxes ProductName and ProductType so now my View Method would look like this

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.

所以我想这是 Prefix 的用武之地,但我不知道如何使用它.我也不知道如何同时使用它和排除.

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.

谁能举个例子?

推荐答案

如果您认为您有...

<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)

您应该注意,如果您将方法参数命名为 p,MVC 会自动为您执行此操作.

You should note that MVC would do this automatically for you if you named your method argument p.

如果您尝试同时绑定多个实体(例如两个名称字段),前缀会非常有用.

The prefix can be very useful if you're trying to bind multiple entities at the same time (e.g. two name fields).

要对某些属性使用 exclude 绑定(即避免人们以伪造的形式传入 ProductId),只需将属性名称设置为 exclude

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

 public ActionResult([Bind(Prefix="p", Exclude="ProductId")]Product product)

这将确保您的实体上的 ProductId 永远不会被设置.

This will ensure that the ProductId on your entity never gets set.

如果你想绑定两个完全不同的字段名称,例如键入 ProductType,您可以查看自定义模型绑定或自己从 FormCollection 中获取字段.

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.

这篇关于如何使用绑定前缀?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆