views:

215

answers:

1

I have a View that renders something like this:

alt text

"Item 1" and "Item 2" are <tr> elements from a table.

After the user change "Value 1" or "Value 2" I would like to call a Controller and put the result (some HTML snippet) in the div marked as "Result of...".

I have some vague notions of JQuery. I know how to bind to the onchange event of the Select element, and call the $.ajax() function, for example.

But I wonder if this can be achieved in a more efficient way in ASP.NET MVC2.

A: 

Here is an example of the method I use with great success:

In the View:

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<IEnumerable<Namespace.Stuff>>" %>

<asp:Content ID="Content3" ContentPlaceHolderID="head" runat="server">
    <script type="text/javascript">
     $(document).ready(function(){
        $("#optionsForm").submit(function() {
            $("#loading").dialog('open');
            $.ajax({
                type: $("#optionsForm").attr("method"),
                url: $("#optionsForm").attr("action"),
                data: $("#optionsForm").serialize(),
                success: function(data, textStatus, XMLHttpRequest) {
                    $("#reports").html(data); //replace the reports html.
                    $("#loading").dialog('close'); //hide loading dialog.
                },
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                    $("#loading").dialog('close'); //hide loading dialog.
                    alert("Yikers! The AJAX form post didn't quite go as planned...");
                }
            });
            return false; //prevent default form action
        });
    });
    </script>
</asp:Content>

<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">

    <div id="someContent">
        <% using (Html.BeginForm("Index", "Reports", FormMethod.Post, new{ id = "optionsForm" }))
          { %>

          <fieldset class="fieldSet">
            <legend>Date Range</legend>
            From: <input type="text" id="startDate" name="startDate" value="<%=ViewData["StartDate"] %>" />
            To: <input type="text" id="endDate" name="endDate" value="<%=ViewData["EndDate"] %>" />
            <input type="submit" value="submit" />
          </fieldset>

        <%} %>
    </div>

    <div id="reports">
        <%Html.RenderPartial("ajaxStuff", ViewData.Model); %>
    </div>

    <div id="loading" title="Loading..." ></div>
</asp:Content>

In the Controller:

public ActionResult Index(string startDate, string endDate)
{
    var returnData = DoSomeStuff();

    if (Request.IsAjaxRequest()) return View("ajaxStuff", returnData);
    return View(returnData);
}

The above code outlines the basic strategy. You will, of course want to tweak it for multiple partials and multiple forms.

Bradley Mountford
Thanks - it helped!
Glad I could help!
Bradley Mountford