简体   繁体   English

MVC路由共享相同的动作?

[英]mvc routes to share the same action?

I have the following two routes defined in my MVC app.;- At the moment I have two "MVC View content pages" defined 我在MVC应用程序中定义了以下两条路由;-目前,我定义了两个“ MVC查看内容页面”

/ShowName/NameById
/ShowName/Index

However the content on these two pages are identical? 但是,这两页上的内容是相同的吗? Is it possible for two routes to share the same content page? 两条路线可以共享同一内容页面吗? If not then can I a) create a single rule for both routes or b) should I create a usercontrol to share between both content pages to show my data? 如果不是,那么我是否可以a)为两个路由创建一条规则,或者b)我应该创建一个在两个内容页面之间共享以显示数据的用户控件?

    routes.MapRoute(
       "NameById",
       "Name/{theName}/{nameId}",
        new
        {
            action = "NameById",
            controller = "ShowName",
            theName = "Charley"
        }
        ,new { nameId = @"\d+" }
   );

    routes.MapRoute(
       "ShowName",
       "Name/{theName}",
        new
        {
            action = "Index",
            controller = "ShowName",
            theName = "Charley"
        }
   );

EDIT I have read the answers below and I have the following action result methods. 编辑我已经阅读了下面的答案,并且我有以下操作结果方法。 If I remove one of the methods (eg the Index) then how would I rewrite my routes to a single route? 如果删除其中一种方法(例如索引),那么如何将路由重写为单个路由?

public ActionResult Index(string theName)
public ActionResult NameById(string theName, int? nameId)

So the following works url's work? 因此,以下作品网址的作品?

/Name/Charley
/Name/Charley/11234

You could create a partial view for the detail area of the page, keeping the separation of the two actions in case they change at a later point. 您可以为页面的详细区域创建局部视图,以使两个动作分开,以防它们在以后发生变化。 Or you could just 或者你可以

return View("DetailView", model);

But that can introduce an extra string to manage between the two controller actions. 但这会引入额外的字符串来管理两个控制器动作之间。 Since MVC does not support overloading by action name (unless you have a GET/POST pair, one with no arguments), you could just check the {nameId} parameter and see if it is empty/null before using it. 由于MVC不支持按动作名称重载(除非您有GET / POST对,一个不带参数),因此您可以只检查{nameId}参数并在使用前查看它是否为空/空。

Do you really need 2 different routes? 您是否真的需要2条不同的路线? You could make the pattern for your Index route 您可以为索引路线制作图案

Name/{theName}/{nameId}

and make nameId a nullable input to your action. 并将nameId设为您的操作的可空输入。 Then just add some logic to your action which checks whether nameId has a value and acts accordingly. 然后只需在您的操作中添加一些逻辑,即可检查nameId是否具有值并采取相应的行动。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM