Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add @Html.TextBox value from ViewBag

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?

like image 361
Villi Katrih Avatar asked Aug 25 '11 12:08

Villi Katrih


People also ask

How pass ViewBag value to TextBox in MVC?

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.

How do you assign a ViewBag value in view?

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.

Can we use ViewBag to pass data from view to controller?

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.


1 Answers

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

like image 60
Manatherin Avatar answered Sep 20 '22 14:09

Manatherin