Roberto Becher
Roberto Becher

Reputation: 164

How to set value to @Html.TextBox() in ASP.NET C# using @Viewbag in MVC3

I wanted to set a data into the html textbox. I've tried this code:

 @Html.TextBox("LastName", @value = @ViewBag.FBUserLastName, new { @style = "width: 300px;", @id = "LastName" })

Unfortunately, it showed an error. I've based that code from this Value not set via ViewData dictionary

Upvotes: 2

Views: 20659

Answers (2)

Michael Brown
Michael Brown

Reputation: 9153

@Html.TextBox(
  "LastName", 
  ViewBag.FBUserLastName, 
  new { @style = "width: 300px;"})

It's a function. The second parameter is the value. Also you can leave the @id from the anonymous type because it's passed in the first parameter.

Upvotes: 0

Brandon
Brandon

Reputation: 69983

Try this

@Html.TextBox("LastName", 
   (string)ViewBag.FBUserLastName, 
   new { @style = "width: 300px;", @id = "LastName" })

You don't need the @value.

Also, you don't need the @ in front of ViewBag, because since you've already called @Html.TextBox, it is already looking for code.

You also apparently need to cast the ViewBag property to a string.

Upvotes: 6

Related Questions