In this article I will explain with an example, how to assign ViewBag value to TextBox in ASP.Net MVC Razor.
This article will illustrate how to assign ViewBag value to TextBox created using Html.TextBox helper function 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.
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();
The View consists of a TextBox created using Html.TextBox helper function. The ViewBag object is passed as the second parameter i.e. the value of the TextBox.
Note: ViewBag is a dynamic object while, the Html.TextBox helper function accepts Object DataType and hence it is necessary to typecast the ViewBag object to Object DataType.
    Layout = null;
<!DOCTYPE html>
    <meta name="viewport" content="width=device-width"/>
    @Html.TextBox("Name", (object)ViewBag.Name)