Monkey Throws Bananas

This sample primarily illustrates using htmlAttributes with the Html.TextBox method to add arbitrary attributes to the rendered html.

All the concepts this sample illustrates:

  • Posting a form.
  • Using the HtmlHelper TextBox method.
  • Using htmlAttributes to add arbitrary attributes to a rendered input field via the TextBox HtmlHelper method.
  • Using ViewData[""] to move data around from controller to view.

A monkey just threw 0 banana(s) at a tiger.

Discussion

The thing of primary interest here is the call to the HtmlHelper class to create a text field. Here is what the form looks like server-side:

    
< %= Html.TextBox("NumberOfBananasThrown", ViewData["NumberOfBananasThrown"], new { size = "3", fungus = "green" }) %>

This adds two attributes to the input field, "size" and "fungus". The "fungus" attribute is ignored because it is not a real attribute, but that doesn't stop you from adding it. When the text field itself is rendered, it looks like this:

    

Nice.

For your reference, the controller actions for this are as follows:

        public ActionResult MonkeyThrowsBananas()
        {
            ViewData["NumberOfBananasThrown"] = 0;

            return View();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult MonkeyThrowsBananas(int? NumberOfBananasThrown)
        {
            if (NumberOfBananasThrown.HasValue)
                ViewData["NumberOfBananasThrown"] = NumberOfBananasThrown.Value;

            return View();
        }