ActionResult参数为空控件

时间:2012-05-15 14:17:32

标签: asp.net-mvc-3 razor null actionresult url-parameters

我如何控制ActionResult null参数?。我尝试为id而无法工作。

控制器:

public ActionResult Languages(int id)
{
    if(id==null)
    {
      id = 0;
    }
    var query = from n in se.Languages
                orderby n.Language ascending
                select n;
    return View(query.Skip(id * 10).Take(10));
}

global.asax中:

    routes.MapRoute(
        null,
        "{controller}/{action}", // URL with parameters
        new { controller = "Home", action = "Languages" } // Parameter defaults
    );

    routes.MapRoute(
        null,
        "{controller}/{action}/page/{id}", // URL with parameters
        new { controller = "Home", action = "Languages", id = UrlParameter.Optional } // Parameter defaults
    );

1 个答案:

答案 0 :(得分:2)

int不可为空尝试

public ActionResult Languages(int? id)

if(!id.HasValue)
    //...

或者

public ActionResult Languages(int id = 0)

或者您可以在路由中提供默认值

routes.MapRoute(
    null,
    "{controller}/{action}/page/{id}", // URL with parameters
    new { controller = "Home", action = "Languages", id = 0 } // Parameter defaults
);