Im using MVC 3 asp.net
How can I add an item from ViewBag
to html.TextBox
like this:
@Html.TextBox("txtName",@ViewBag.Parameters.Name)
I tried this too:
@Html.TextBox("txtName","@(ViewBag.Parameters.Name)")
nothing seems to work.
any suggestions?
TextBoxFor you must define a model type that defines the property that you wish to bind. Otherwise you have to use Html. TextBox and set the value manually from ViewBag . As others have said, you will make your life much easier if you use a statically typed model and take advantage of the inbuilt MVC model binding.
You can assign a primitive or a complex type object as a value to ViewBag property. You can assign any number of properties and values to ViewBag. If you assign the same property name multiple times to ViewBag, then it will only consider last value assigned to the property.
ViewBag itself cannot be used to send data from View to Controller and hence we need to make use of Form and Hidden Field in order to pass data from View to Controller in ASP.Net MVC Razor.
A View with just
@{
ViewBag.Title = "Index";
}
@Html.TextBox("txtTitle", (string)ViewBag.Title)
works fine with me (notice the cast of the viewbag data to string because Extension methods cannot be dynamically dispatched.) also you will obviously have to change ViewBag.Title to your property
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With