In this article I will explain with an example, how to set Label value inside Controller in ASP.Net MVC Razor.
This article will illustrate how to set value of Label in ViewBag object inside Controller and later use the ViewBag object to set value in Label inside View in ASP.Net MVC Razor.
Note: For beginners in ASP.Net MVC, please refer my article ASP.Net MVC Hello World Tutorial with Sample Program example.
 
 
Controller
The Controller consists of the following Action method.
Action method for handling GET operation
Inside this Action method, a string value is set into a ViewBag object i.e. Name and simply the View is returned.
public class HomeController : Controller
{
    // GET: Home
    public ActionResult Index()
    {
        ViewBag.Name = "Mudassar Khan";
        return View();
    }
}
 
 
View
The View consists of a Label created using Html.Label helper function. The ViewBag object is passed as the first parameter i.e. the value of the Label.
Note: ViewBag is a dynamic object while, the Html.Label helper function accepts String DataType and hence it is necessary to typecast the ViewBag object to String DataType.
 
@{
    Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width"/>
    <title>Index</title>
</head>
<body>
    @Html.Label((string)ViewBag.Name)
</body>
</html>
 
 
Downloads