代码之家  ›  专栏  ›  技术社区  ›  Parminder

重写方法asp.net mvc

  •  1
  • Parminder  · 技术社区  · 15 年前

    我可以重写ActionResult方法吗?假设我在accountcontroller中有这样的方法索引

    公共操作结果索引() {

    返回视图(); }

    我能再要一个同名但参数不同的方法吗 喜欢 公共操作结果索引(int userid) {

    返回视图(); }

    我不想这样叫它 http://something/accounts/index/11 我只想说 http://something/accounts/11

    你也可以看看stackoverflow的东西 如果你去 https://stackoverflow.com/users 我觉得用户是控制器,默认操作是index,所以不要把它称为显式的。 现在如果你输入 https://stackoverflow.com/users/96346/parminder 这两个参数是96346和parminder

    我希望这是有意义的。

    global.asax中的条目是什么

    当做 帕梅德

    3 回复  |  直到 12 年前
        1
  •  0
  •   Community CDub    8 年前

    看看我的问题 here

    我认为你可以通过破解一些方法属性来实现,但我认为如果你编写另一个方法,然后为它添加一个路由,这样会更干净。

    public ActionResult Index()
    {
        return View();
    } 
    
    public ActionResult UserInfo(int id)
    {
        //some stuff
        return View(modelObject);
    }
    

    然后提供一条路线,例如:

    routes.MapRoute("UserInfo", //route name
                    "Accounts/{id}",
                    new 
                    { 
                        controller = "Accounts",
                        action = "UserInfo",
                        id=UrlParameter.Optional 
                    });
    
        2
  •  1
  •   Darin Dimitrov    15 年前

    可以执行操作重载(同一控制器上具有相同名称的两个具有不同参数的操作),但它们应该在不同的http谓词上被调用。这是ASP.NET MVC应用程序中的常见模式:一个操作可通过get访问,该操作呈现包含窗体的视图,另一个操作将由该窗体发布到:

    public class HomeController: Controller
    {
        public ActionResult Index()
        {
            return View();
        }
    
        [HttpPost] // [AcceptVerbs(HttpVerbs.Post)] for ASP.NET MVC 1.0
        public ActionResult Index(SomeViewModel model)
        {
            if (ModelState.IsValid)
            {
                // TODO: validation passed => do something with the model
            }
            return RedirectToAction("index");
        }
    }
    

    不需要为此修改路由,它可以与默认路由一起工作。

        3
  •  0
  •   Wikser    15 年前

    你想结束- 负载 方法。但你不需要。

    只需使参数为空:

    public ActionResult Index(int? userid)
    {
       return (userid.HasValue) ? ShowUser(userid.Value) : ShowOverview();
    }
    

    在本例中,可以采用默认的路线图。

    对于您(已更改的)需求,您确实需要使用约束修改路由。

    routes.MapRoute("directaccount", "Accounts/{userid}/{someotherparam}",
        new { controller="Accounts", action="ShowAccountByID", someotherparam=null }
        new { userid=@"\d+"});
    
    *here goes the rest*
    

    Reg-Ex确保您的其他通话不会被这条线路吃掉。这是未经测试的。我不建议对此功能使用重载。