Ajax.BeginForm: Clear Form After Submit

If you are using ASP.NET MVC, here is a simple tip on how to clear an ajax form after successfully submitting it with a little help from jQuery.

The first step is to get the jQuery Form Plugin, add it to your Scripts folder and then add a script reference to it in your masterpage. jQuery is already included in the projects since the release of the MVC so you don’t need to download and include it.

<script src="../../Scripts/jquery-1.2.6.js" type="text/javascript"></script>
<script src="../../Scripts/jquery.form.js" type="text/javascript"></script>

You can then create a function that will call the clearForm function from the Form Plugin.

<script type="text/javascript">
   function done() {
       $('form').clearForm();
   }
</script>

Now you can use the OnSuccess callback from the Ajax.BeginForm helper to point to the done() function we just created. This function will be called automatically after the form submit completed successfully.

<% using (Ajax.BeginForm("SaveComment", new AjaxOptions { 
         UpdateTargetId = "feedback", 
         InsertionMode = InsertionMode.Replace, 
         OnSuccess = "done"}))
{ %>

Here is the complete code:

<script type="text/javascript">
            function done() {
                $('form').clearForm();
            }
    </script>
    <h2 id="feedback"></h2>
    <fieldset>
        <% using (Ajax.BeginForm("SaveComment", new AjaxOptions { 
               UpdateTargetId = "feedback", 
               InsertionMode = InsertionMode.Replace, 
               OnSuccess = "done"}))
           { %>
            <dl>
                <dd><%= Html.TextBox("Comment.Author")%></dd>
                <dd><input type="submit" title="Submit" /></dd>
            </dl>
        <% } %>
    </fieldset>

 

ASP.NET MVC: ListBox

The Html.ListBox helper is a good choice if you need to represent many-to-many relationships in a form.

Lets say you have a many-to-many between the Posts table and the Categories table. When you are creating a new post you need to select all the categories that it belongs to. When you are editing a post you need to show the categories it already belongs to in order to make a new selection (or not).

 The ListBox would allow you to make all the selections necessary, so the Action and the View for the New Post would need something like this:

Action:

[AcceptVerbs("GET")]
public ActionResult New()
{
        ViewData["Categories"] = _postService.GetCategories();
        return View();
}

View:

<%= Html.ListBox("CategoryList", new MultiSelectList((IList<Category>)ViewData["Categories"], "ID", "Name"))%>

And the View and Action for the Edit would be like this:

Action:

[AcceptVerbs("GET")]
public ActionResult Edit(int? id)
{
        int postId = id ?? 0;
        //get the post that is being edited
        Post post = _postService.GetPost(postId);
        //get all the categories
        ViewData["Categories"] = _postService.GetCategories();
        //get the id's of the categories to which the post belongs
        ViewData["CategoryIDs"] = post.Categories.Select(c => c.ID);
        return View(post);
}

View:

<%= Html.ListBox("CategoryList", new MultiSelectList((IList<Category>)ViewData["Categories"], "ID", "Name", (IEnumerable<int>)ViewData["CategoryIDs"]))%>

Note that this time I had to pass an extra parameter to the ListBox method which is a list of the categories ID’s that are already associated with the Post. This list will be used to make the initial selection in the ListBox rendered in your HTML.

One last thing you need to know is how to get the ID’s of the selected categories back in your action. This is pretty simple as well. The Form will have a CategoryList item that will have a comma separated string with all the selected lines, all you need to do is split this in a array of strings and them save them to the database as you see fit.

string[] selected = Request.Form["CategoryList"].Split(',');

I hope this tip is useful to others that are testing the MVC Framework.

ASP.NET MVC: DropDownList

Here is an example of how to use the Html.DropDownList helper method available in the MVC framework to generate a combo in you page.

Let’s use the Northwind example and say that you want to create a product and in the product for you need to select a category to which this product belongs in a dropdownlist.

The first step is in the select the list of categories in the appropriate controller action. In my case I’m going to use the new Action.

public ActionResult New()
{
    ViewData["CatList"] = new SelectList(_db.Categories.ToList(), "CategoryID", "CategoryName");
    return View();
}

Notice that I used the SelectList class. In this case I used the constructor that takes 3 parameters:

  1. The list of categories I got from my Linq DataContext
  2. The name of the property of the Category class that has the ID value that is going to be stored in the select list and which will be the value that actually is passed to the Product class
  3. The name of the property of the Category class that has the value I want to display to the user

The SelectList class will be used by the DropDownList helper to generate the html code. Here is part of the View code:

...
<tr>
       <td>Category:</td>
       <td><%= Html.DropDownList("CategoryID",(SelectList)ViewData["CatList"]) %></td>
</tr>
...

 

Where is the RenderPartial method?

I was coding an demo application using the ASP.NET MVC Beta 1 and all the sudden I couldn’t access the RenderPartial method of the HtmlHelper from a Helper method I was writing. So where did it go?

I noticed that in the previous release the RenderPartial was a static method but in the Beta 1 they changed it to an Extension Method for the and it now lives in the namespace ’’‘System.Web.Mvc.Html’’’. So if you want to use this method all you need is to import this namespace in the classes where you are using the System.Web.Mvc.HtmlHelper class. In the Views you will notice that it keeps working as if nothing changed, that’s why the MVC’s development team has already added the System.Web.Mvc.Html namespace in the web.config. Here is the namespace node of the web.config the in MVC Beta 1.

<namespaces>
   <add namespace="System.Web.Mvc"/>
   <add namespace="System.Web.Mvc.Ajax"/>
   <add namespace="System.Web.Mvc.Html"/>
   <add namespace="System.Web.Routing"/>
   <add namespace="System.Linq"/>
   <add namespace="System.Collections.Generic"/>
 </namespaces>

 

ASP.NET MVC Beta was released

The beta version of the ASP.NET MVC framework is out of the oven! This is good news people, means that it’s only a few tweaks a way from the final version. ScottGu says on his blog that there are features to be implemented but the core is done and there won’t be any more major changes. Here are a few resources for you:

Download ASP.NET MVC Beta The asp.net site has a lot of articles and videos