MVC的行动与可选参数 - 这是更好?这是、可选、行动、参数

由网友(╬最终メ幻想╬)分享简介:有什么利弊/使用以下两种方式在你的行动签名的缺点:公众的ActionResult行动(INT?X)//获取MVC绑定空当没有提供参数{如果(x.HasValue){// 做一点事}}或公众的ActionResult行动(INT X = NULL)// C#可选的参数(虚过载){如果(x.HasValue){//...

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

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

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

解决方案

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

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

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

在我的例子我已经使用的查询字符串参数的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.

阅读全文

相关推荐

最新文章