开发者

Can I do MVC method overloading with a variable that can be null?

Basically put, I have a MVC project and I just have the default route.

(Question edited as after testing and re-reading my question, I am sure the error is just because ints can not be null)

I have read complex answers on here about overloading, but if I want to have two different results for a page call, say one if it is null and the other if it is passed a request, is the following sufficient?

    public ActionResult Details(int? id)
    {
        if(id != null)
            id=1;
        return View(id);
    }

and then can this be extended to more complex situations such as public ActionResult Details(int? id, string bla, string bla2) and just have a开发者_如何转开发 combination of null checks to return different views, or am I best implementing a solution such as on this answer.


While the last parameter is optional, the mapping engine doesn't find an Action for the route without the id parameter that fits - thus the error. You have two possibilites - either the way you described, or by making a default action:

public ActionResult Details ()
{
  return View(); //default view for this controller, could be a redirect as well
}

Keep in mind though, this won't work if your id is something nullable (in the case of a string for example, anything Nullable<T>), as the mapping engine will find ambigious overloads. In that case, there is no way around the null check.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜