Question

I'm new to MVC and also new to Stackoverflow. I'm not working with any Database but I simply want to display Title and Massage on 1 View by 2 different Controllers. I want in my Index.cshtml file the @ViewBag.Title display from HomeController.cs file and the @ViewBag.Massage display from OtherController.cs file. How can I do this and how to reference or attach OtherController.cs to Index.cshtml? Please don't tell me that I'm asking for something like how to attach stylesheet to html but it's not possible with MVC.

If it's really not possible then please tell me how to do this by partial views with having a _Layout.cshtml file. Because I don't want to write too much in my View Files.

Thank You in Advance!

RouteConfig.cs

routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home",
                                action = "Index",
                                id = UrlParameter.Optional
                              }
               );

HomeController.cs

public ActionResult Index()
        {
            ViewBag.Title = "";
            return View();
        }

OtherController.cs

public ActionResult Index()
        {
            ViewBag.Massage = "";
            return View();
        }

Index.cshtml

<title>@ViewBag.Title</title>

<p>@ViewBag.Massage</p>
Was it helpful?

Solution

Index action method will be same in home controller but in Other controller you should return partial view .

   public ActionResult PartialIndex()
    {
        ViewBag.Massage = "Message from Partial View";
        return PartialView();
    }

Partial view

 <p>@ViewBag.Massage</p>

In main View you can call this.

  <h1>@ViewBag.Title.</h1>
  <h2>@{Html.RenderAction("IndexPartial");}</h2>

OTHER TIPS

I do not know if you can but if you would do it the proper way then you would make 2 different views with the specific content and then each ActionResult refers to a view. In other words the best way of doing it is not the way you are trying to do it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top