简体   繁体   中英

How can I get MVC3 to call a view with a different name?

I have the following in my controller:

    public ActionResult Tests()
    {
    }

    public ActionResult Test()
    { 
    }

I would like both to go to the Test.cshtml view when I return. Can someone tell me if this is possible. I know the Test one will by default go to Test.cshtml but what about Tests? How can I direct that to the Test.cshtml?

Alternatively should I keep these as two views and use RenderPartial? If I did that then how can I pass my Model into the RenderPartial view?

Thanks,

Provide view name when returning

It seems you haven't really checked out method overloads. When returning from controller actions there are several possible overloads that return ViewResult result. One of them allows you to provide view name:

public ActionResult Tests()
{
    ...
    // provide the model too if you need to
    return View("Test", model);
}

public ActionResult Test()
{ 
    ...
    // provide the model too if you need to
    return View("Test", model);
}

Html.RenderPartial has overloads too

The same is true about Html.RenderPartial where you can also provide model while calling it. Check its extension methods here .

I suggest you check documentation because you'll understand much more.

The overload of View allows you to explicitly name which view to use.

public ActionResult Tests()
{
  return View("Test");
 }

 public ActionResult Test()
 { 
   return View("Test");
 }

Use this Overload

return View("Test");

This will return view named "Test" despite of the calling action

是的,只需指定视图名称:

return View("Test");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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