Mridul Raj
Mridul Raj

Reputation: 999

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

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

Upvotes: 0

Views: 24099

Answers (1)

Yasser Shaikh
Yasser Shaikh

Reputation: 47774

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

Upvotes: 5

Related Questions