多个操作可以提供相同的视图吗?

时间:2014-03-20 21:45:26

标签: c# asp.net asp.net-mvc-4

我的应用程序中有2个页面将布局相同。我想为每个视图使用相同的视图,并通过控制器传递内容。如何在我的控制器中进行设置:

这是我的导航部分外观:

@{
    Dictionary<string, string> links = new Dictionary<string,string>();
    links.Add("home", "Index");
    links.Add("neurosurgical", "Neurosurgical");
    links.Add("pain management", "PainManagement");
    links.Add("staff", "Staff");
    links.Add("patient resources", "PatientResources");
    links.Add("contact", "Contact");
}
<nav id="main_menu">
    <ul class="primary_menu">
        @foreach(var link in links)
        {
            <li class="@(link.Value == ViewContext.RouteData.Values["Action"].ToString() ? "active" : "")">
                @Html.ActionLink(link.Key, link.Value)
            </li>
        }
    </ul>
</nav>

上面列出的类似页面是NeuroSurgical和PainManagement。我的控制器现在看起来像这样:

namespace ****************.Controllers // Namespace redacted
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";

            return View();
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your app description page.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }
    }
}

About是我设置的视图文件,用作两个页面的模板。我是否为每个页面创建操作并将它们指向About.cshtml?怎么样?

2 个答案:

答案 0 :(得分:5)

public ActionResult Contact()
{
    ViewBag.Message = "Your contact page.";
    return View("About");
}

答案 1 :(得分:2)

您需要为每个页面创建操作并让它们使用相同的视图。像这样:

    public ActionResult NeuroSurgical()
    {
        //create your model, etc here
        return View("SharedViewNameHere", model);
    }

    public ActionResult PainManagement()
    {
        //create your model, etc here
        return View("ViewNameHere", model);
    }