How to create and use variables in MVC

Home > Search > How-to
  by

Let's start with a very simple variable. The following can be entered in a razor view file.

@{
    string sample = "Hello World";
}

@Html.Raw(sample)

 

This would produce the following.

 


Text can be passed from the Controller to a View using ViewBag.Message.

CONTROLLER

public ActionResult Index()
{
    ViewBag.Message = "Hello World";
    return View();
}

VIEW

@ViewBag.Message

 

This would produce the following.

 


To pass more than one variable to the view, do the following.

CONTROLLER

public ActionResult Index()
{
    var abc = "Hello";
    ViewBag.abc = abc;

    var xyz = "World";
    ViewBag.xyz = xyz;

    return View();
}

VIEW

@Model.site
@Model.username

@ViewBag.abc
@ViewBag.xyz

This would produce the following.



Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.




Please enter in the box below so that we can be sure you are a human.




Comments