如何从 MVC 中的一个控制器加载两个视图

How to load Two views From one Controller in MVC

我有两个 Html link <a href="@Html.ActionLink("advetisement","sample")"></a><a href="@Html.ActionLink("advetisement1","sample")"></a> 当我单击 First Link 时,它会转到 Sample controller 并转到 advetisement Methode 和 returns View public ActionResult advetisement{ // here iam reciveing data to variable return view() } 现在它返回到视图并且数据被绑定并显示 Page.Now 当我点击第二个 link 它应该去相同的控制器(广告)和 return 相同的数据但是视图应该有所不同,因为 html 样式已更改。

您可以从同一控制器操作加载两个不同的视图:

if (model.SomeCondition == true)
{
   return View("ViewName1", model);
}
return View("ViewName2", model);

然后使用您的视图模型来存储确定显示哪个视图的条件:

public class MyViewModel
{
    public bool SomeCondition  { get; set;}
    public object Data { get; set; }
}

我认为最简单的方法就是使用不同名称的两个动作。当然,应该将代码重复提取到单独的方法中。像这样:

    public ActionResult Advertisement()
    {
        return AdvertisementInternal("Advertisement");
    }

    public ActionResult Advertisement1()
    {
        return AdvertisementInternal("Advertisement1");
    }

    private ActionResult AdvertisementInternal(string viewName)
    {
        // filling ViewBag with your data or creating your view model
        ...
        return View(viewName);
    }

但是如果适当的方式是两种视图的唯一操作,那么您应该有一个标志来区分视图。它可以添加到 URL。像这样:

    // on the view
    @Html.ActionLink("Link1", "Advertisement", "Sample", new { Id = "View1" }, null)
    @Html.ActionLink("Link2", "Advertisement", "Sample", new { Id = "View2" }, null)

    // in the controller
    public ActionResult Advertisement(string id)
    {
        if (id == "View1" || id == "View2")
        {
            // filling ViewBag with your data or creating your view model
            ...
            return View(id);
        }
        return HttpNotFound();
    }