C# 可选对象操作 MVC 参数
是否可以通过某种方式将对象指定为具有默认值的 MVC 参数?
例如,
public virtual ViewResult Index(RequirementFilters requirementFilters)
我想初始化 RequirementFilters 上的几个参数的值?
目前我正在做的事情是
public virtual ViewResult Index(int status=1, bool required =false)
我想创建一个过滤器对象,以便我可以重复使用它,但我无法找出在操作参数中为对象设置默认值的方法。
谢谢格雷姆
Is it possible to specify an object as a parameter in MVC with default values in some way?
E.g.
public virtual ViewResult Index(RequirementFilters requirementFilters)
I'd like to initialize the values of a couple of parameters on RequirementFilters?
At the moment I am doing
public virtual ViewResult Index(int status=1, bool required =false)
I wanted to create a Filter Object so I could re-use it but I can't figure out way of setting defaults for the object in the Action Parameters.
Thanks
Graeme
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以创建自定义 ActionFilter 属性并在其中创建过滤器对象的实例。您可以通过自定义属性提供一些属性。
下面是一个示例:
ParameterName
是操作方法中参数的名称(在您的情况下是requirementFilters
)。您还可以通过提供
SettingsType
来指定将实例化的实际类型。You could create a custom ActionFilter attribute and create an instance of your Filter Object there. You can provide some properties through the custom attribute.
Here's an example:
ParameterName
is the name of the argument in the action method (requirementFilters
in your case).You can also specify actual type that will be instantiated by providing
SettingsType
.用户有时更喜欢在屏幕上看到默认值,而不是让系统在内部隐藏默认值。
拥有默认值的更好方法是通过将默认值与默认值一起渲染,在 HTML 中实际显示 int UI 上的默认值。这样,当有人发布页面时,您预渲染的默认值也会发布并绑定到模型。
因此,尝试看看您是否可以使用默认值进行渲染,无论您正在渲染并发布到
Index
操作。最后,如果您不能这样做,那么在创建对象时,是什么阻止您在无参数构造函数中使用默认值初始化属性呢?
编辑
或者您可以使用 C# 语言功能 null 合并运算符来实现默认值。请参阅此处了解相关信息。
Users sometimes prefer to see the defaults on screen, rather than allowing the system to hide the defaults internally.
A better way of having defaults will be to actually show the defaults on int UI, in the HTML by rendering it with together with the defaults. That way when someone posts the page, the defaults which you pre-rendered is also posted and binded to the model.
So try and see if you can render with defaults whatever for you are rendering and posted to the
Index
action.Finally, if you can't do it that way, what is preventing you from initializing the properties with default values in the no-arg constructor while creating the object?
EDIT
Or you can use the C# language feature the null coalescent operator to implement defaults. Look here to read about it.
只要您不需要更改每个操作的默认值,您就可以在模型的默认构造函数中设置它们。
As long as you don't need to change the defaults per action, you can set them in the default constructor of the Model.