Venkata Krishna Reddy
Venkata Krishna Reddy

Reputation: 672

How to load Two views From one Controller in MVC

i have two Html links <a href="@Html.ActionLink("advetisement","sample")"></a> and <a href="@Html.ActionLink("advetisement1","sample")"></a> When i click First Link it goes to Sample controller and goes to advetisement Methode and returns View public ActionResult advetisement{ // here iam reciveing data to variable return view() } now it retuns to view and data is binded and displays Page.Now when i click second link it should go to Same controller(advetisement) and return same Data but view should be diffrent since html styling is changed.

Upvotes: 0

Views: 5437

Answers (2)

Marko
Marko

Reputation: 13233

You can load two different views from the same controller action:

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

Then use your view model to store the condition which determines which view to display:

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

Upvotes: 5

Viktar Tserashchuk
Viktar Tserashchuk

Reputation: 368

I think the easiest way is just having two actions with different names. Of course, code duplication should be extracted to the separate method. Something like this:

    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);
    }

But if an appropriate way is the only action for both views then you should have a flag to distinguish the views. It can be added to URL. Something like this:

    // 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();
    }

Upvotes: 0

Related Questions