用不同的签名控制器操作方法 [英] Controller Action Methods with different signatures

查看:110
本文介绍了用不同的签名控制器操作方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图让我的网址中的文件/ ID 格式。我猜我应该有我的控制器有两个指数的方法,其中一个参数和一个与不行。但是,我在下面的浏览器收到此错误信息。

I am trying to get my URLs in files/id format. I am guessing I should have two Index methods in my controller, one with a parameter and one with not. But I get this error message in browser below.

反正这是我的控制器方法:

Anyway here is my controller methods:

public ActionResult Index()
{
    return Content("Index ");
}

public ActionResult Index(int id)
{
    File file = fileRepository.GetFile(id);
    if (file == null) return Content("Not Found");
    else return Content(file.FileID.ToString());
}

更新:与添加路由完成。感谢Jeff

Update: Done with adding a route. Thanks to Jeff

推荐答案

您只能<一个href=\"http://stackoverflow.com/questions/436866/can-you-overload-controller-methods-in-asp-net-mvc\">overload如果他们的论点和动词,不只是参数不同操作的。在你的情况,你会希望有一个可为空ID参数一个动作,像这样:

You can only overload Actions if they differ in arguments and in Verb, not just arguments. In your case you'll want to have one action with a nullable ID parameter like so:

public ActionResult Index(int? id){ 
    if( id.HasValue ){
        File file = fileRepository.GetFile(id.Value);
        if (file == null) return Content("Not Found");
            return Content(file.FileID.ToString());

    } else {
        return Content("Index ");
    }
}

您也应该阅读菲尔哈克的一个方法是如何变成一个行动

You should also read Phil Haack's How a Method Becomes an Action.

这篇关于用不同的签名控制器操作方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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