-1

Hello i am new in MVC C#, and have some issues

I have controller like this

public class HomeController : Controller
        {
            //
            // GET: /Home/

            public ActionResult Index()
            {

                return View();
            }
}

I want to pass some varible like HOME to current view, how to accomplish that, and how to show that in view? lik @what

tereško
  • 58,060
  • 25
  • 98
  • 150
Schneider
  • 2,446
  • 6
  • 28
  • 38
  • This is adressed in the first ASP.NET MVC tutorials and I'd suggest you go take a good look at them. You [start by using the ViewBag](http://www.asp.net/mvc/tutorials/mvc-5/introduction/adding-a-view), then you go about [adding models](http://www.asp.net/mvc/tutorials/mvc-5/introduction/examining-the-edit-methods-and-edit-view) to pass values from controllers to views. – CodeCaster Mar 25 '14 at 09:29
  • possible duplicate of [ViewBag, ViewData and TempData](http://stackoverflow.com/questions/7993263/viewbag-viewdata-and-tempdata) – CodeCaster Mar 25 '14 at 09:31

2 Answers2

1

for a simple variable add it to the ViewBag and then reference it via @Model

for example

        public ActionResult Index()
        {

            var Home = "No place like";
            ViewBag.Home = Home;
            return View();
        }

In View:

@ViewBag.Home 

will display what you've set.

As you want to add more complex data structures you will want to pass through a model object to the view.

You can pass this like

    public ActionResult Index()
    {

        var myViewModel = new MyViewModel(); // set up view model with data

        return View(myViewModel);
    }

and then you can reference that from the view too!

{
    @model = MyViewModel;
}

and refer to it later

<p>@model.PropertyName</p>
Johnno Nolan
  • 29,228
  • 19
  • 111
  • 160
0

To avoid headaches and if you have a small number of variables (really small) you can use the ViewBag.

Controller:

ViewBag.MyVarName = "My var content or whatever";

View:

@ViewBag.MyVarName @* this prints the var *@

If you have a larger number of variables, you should use models.