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

19,891

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.

Share:
19,891
Roberto Becher
Author by

Roberto Becher

Updated on June 05, 2022

Comments

  • Roberto Becher
    Roberto Becher almost 2 years

    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

  • Roberto Becher
    Roberto Becher over 12 years
    I got this error : Compilation Error Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately. Compiler Error Message: CS1973: 'System.Web.Mvc.HtmlHelper<dynamic>' has no applicable method named 'TextBox' but appears to have an extension method by that name. Extension methods cannot be dynamically dispatched. Consider casting the dynamic arguments or calling the extension method without the extension method syntax.
  • 赵君君
    赵君君 over 12 years
    @Roberto, see update. Cast the ViewBag.FBUserLastName to a string
  • Roberto Becher
    Roberto Becher over 12 years
    I got this error : Compilation Error Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately. Compiler Error Message: CS1973: 'System.Web.Mvc.HtmlHelper<dynamic>' has no applicable method named 'TextBox' but appears to have an extension method by that name. Extension methods cannot be dynamically dispatched. Consider casting the dynamic arguments or calling the extension method without the extension method syntax.
  • 赵君君
    赵君君 over 12 years
    @Roberto, no problem. If this solved your problem, please don't forget to mark it as the accepted answer when you are able.
  • Michael Brown
    Michael Brown over 12 years
    That's my fault. Brandon got it right. I forgot to cast it to string
  • Mridul Raj
    Mridul Raj almost 12 years
    This is not working for me. No mattere what value i set to ViewBag.FBUserLastName , my textbox is empty