How to assign value to text input from viewbag when viewbag contains value passed from controller

asp.net-mvc-3viewbag

Im new to ASP.NET MVC3.

I tried to pass value from controller to a view and then assign that value to text input inside the view.

I tried with viewbag and viewdata. While debugging i could find the value inside viewbag but when my view appers in the browser, textbox is empty.

However , if i assign some value to viewbag from within .cshtml file, it work.

Controller

public ActionResult Contact()
{
 ViewBag.fullname = "Hello";
 ........
 return view();
}

View

@{ ViewBag.lastname = "Hello";
}
@Html.TextBox("fullname", (string)ViewBag.fullname)
@Html.TextBox("lastname", (string)ViewBag.lastname)

output

first textbox – empty

second textbox – Hello

Best Answer

Try this out...

Controller

public ActionResult Contact()
{
 ViewBag.fullname = "Hello";
 ViewBag.lastname = "World";

 return View();
}

View

@Html.TextBox("fullname", (string)ViewBag.fullname)
@Html.TextBox("lastname", (string)ViewBag.lastname)

Also check this

Related Topic