Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to have 2 views associated with one action?

I have the following custom route

routes.MapRoute("custom", "Groups/{groupname}/{action}/{id}", new { controller = "Groups", action = "Index", id = UrlParameter.Optional });

This custom route is to achieve the following url schema

  • Groups/pokerclub/members/ - list all the members of pokerclub group.
  • Groups/pokerclub/members/bob - list member details of bob.

I tried the following but it doesnt work. it confuses asp .net mvc of which action to select.

public ActionResult Members(string groupName, string id)
    {
        return View();
    }

    public ActionResult Members(string groupName)
    {
        return View();
    }

There are two possible solutions that i could think of:

  • Have different action name. e.g. Memberlist action and member action.
  • Handle this in the view using simple if statement.

I very much want to maintain my url scheme. thus, as per my original question, how to have two different views associated to one action? Thanks.

RWendi

like image 216
RWendi Avatar asked Dec 13 '25 05:12

RWendi


2 Answers

You can only have one action, but you can perform whatever logic you want inside that action, and you can call views by name:

return View("MyView");

In your example, you would simply return a different view if the id field was null.

like image 182
bhamlin Avatar answered Dec 15 '25 19:12

bhamlin


where it says return View(); It takes parameters and you can get it to use whatever view you would like

return View("Members", model);
like image 40
Keith Nicholas Avatar answered Dec 15 '25 17:12

Keith Nicholas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!