17

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?

2 Answers 2

48

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

Sign up to request clarification or add additional context in comments.

3 Comments

great the (string) fixed everything and i found another way to do what I wanted, like this: <input type="text" name="txtName" value="@(ViewBag.Parameters.Name)" />
In regards to your last comment, you are not making a use of MVC framework and HTML helpers. Yes it has a learning curve and yes it's easier to hack some HTML, pull value from view bag and it all works, but this is not what it was intended for. Please consider using HTML helpers.
I was using an @Html.ActionLink(ViewBag... but I had to change it to @Html.ActionLink((string)ViewBag... The casting was the solution.
1

This will work: @Html.TextBox("txtName",ViewBag.Parameters.Name) assuming that ViewBag.Parameters.Name has a value

Just to elaborate, you are using @ symbol twice, which doesn't make sense.

Good luck

2 Comments

: 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.
@Html.TextBox("txtName",ViewBag.Parameters.Name) and it give compilation error

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.