Generating forms with Html.InputForm()

In the previous recipes, we have taken a look at templated helpers and the MvcContrib input builders. But those forms of streamlining your UI pale in comparison to the MvcContrib InputForm functionality, which is similar to that of ASP.NET MVC's own Html.EditorForModel. With one single line of code, you are able to generate an entire form with all of its fields, input controls, and various other markup that we would like to have, as defined by the input builders.

How to do it...

  1. Start by creating a copy of the project from the last recipe.
  2. We will add a New() method to the HomeController, which will return an instance of our new ExampleModel.
    Controllers/HomeController.cs:
    public ActionResult New() {
    return View(new ExampleModel());
    }
    
  3. Then we need to generate the view for our new action. Be sure to build your project first, so that your ExampleModel is available in the Add View dialog. Then right-click on the action and select Add View. Make this a strongly typed view based on the ExampleModel and have Visual Studio create an empty view.
  4. With our view generated, we are almost ready for the magic. There is one last step though, we need to drag in all the input builder views from the MvcContrib project (located in Dependencies/MvcContrib/InputBuilderTemplates) to the Views/Shared directory in our MVC project.
  5. Inside the view, we can now add the magic that is the Html.InputForm() call. Add this under the h2 tag that was generated for you.
    Views/Home/New.aspx:
    <%= Html.InputForm() %>
    
  6. Now you can hit F5 to run your application. Then navigate to /home/new and see your magic new input form.
    How to do it...

How it works...

This functionality is built on top of the MvcContrib input builders that we covered earlier. Each type has its own view. The InputForm extension method loads the Form.aspx view, which in turn makes a call to Html.InputFields, which then lays out all of the items of the model that is passed into the InputForm.

There's more...

Eric Hexter has a great blog series on InputBuilder (including the InputForm) located here: http://www.lostechies.com/blogs/hex/archive/2009/06/09/opinionated-input-builders-for-asp-net-mvc-using-partials-part-i.aspx.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset