MVC的行动与可选参数 - 这是更好? [英] MVC Action with Optional Parameters -- which is better?

查看:197
本文介绍了MVC的行动与可选参数 - 这是更好?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么利弊/使用以下两种方式在你的行动签名的缺点:

 公众的ActionResult行动(INT?X)//获取MVC绑定空当没有提供参数
{
    如果(x.HasValue)
    {
        // 做一点事
    }
}
 

 公众的ActionResult行动(INT X = NULL)// C#可选的参数(虚过载)
{
    如果(x.HasValue)
    {
        // 做一点事
    }
}
 

解决方案

我从来没有见过在实践中,第二个动作的签名并不能看到它的任何用处。

第一种通常涵盖了所有的场景:

  • 如果没有参数发送( GET / somecontroller /动作)的x参数的值将是行动的内部空
  • 如果斧参数是送的,但它不是一个有效的整数(GET / somecontroller /动作<$ C C $>?X = ABC )的x参数的值将为空动作和的ModelState内将无效
  • 如果斧参数发送及转口货值为presents一个有效的整数(GET / somecontroller /动作<$ C C $>?X = 123 ),那么x将被分配到吧。

在我的例子我已经使用的查询字符串参数的GET请求,但显然同样适用于其他HTTP动词,如果 X 是一个路由参数。

Are there any pros/cons of using the following two alternatives in your action signature:

public ActionResult Action(int? x) // get MVC to bind null when no parameter is provided
{
    if(x.HasValue)
    {
        // do something
    }
}

OR

public ActionResult Action(int? x = null) // C# optional parameter (virtual overload)
{
    if(x.HasValue)
    {
        // do something
    }
}

解决方案

I have never seen the second action signature in practice and can't see any usefulness of it.

The first one usually covers all the scenarios:

  • If no parameter is sent (GET /somecontroller/action), the value of the x argument will be null inside the action
  • If a x parameter is sent, but it is not a valid integer (GET /somecontroller/action?x=abc), the value of the x argument will be null inside the action and the modelstate will be invalid
  • If a x parameter is sent and the value represents a valid integer (GET /somecontroller/action?x=123), then x will be assigned to it.

In my examples I have used GET requests with query string parameters but obviously the same applies with other HTTP verbs and if x was a route parameter.

这篇关于MVC的行动与可选参数 - 这是更好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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