views:

620

answers:

3

Scenario

I am having dropdownlist on a page, now on the change event of it I would like to pull some data from database and then display it.

I am able to do it with postback, I tried using Ajax.Beginform() but it still doing a post back.

<script src="../../Scripts/MicrosoftAjax.js" type="text/javascript"></script>
<script src="../../Scripts/MicrosoftMvcAjax.js" type="text/javascript"></script>

    <%using (Ajax.BeginForm("UpdatePanel", new AjaxOptions { UpdateTargetId = "divDetails" }))
          {%>
        <%=Html.DropDownList("Dinner", (SelectList)ViewData["Dinner"], new { onchange = "this.form.submit();" })%>
        <div id="divDetails">
            <fieldset>
                <legend>Details</legend>
                <% if (Model != null)
                   {%>
                <p>
                    ID:
                    <%= Html.Encode(Model.ID)%>
                </p>
                <p>
                    Title:
                    <%= Html.Encode(Model.Title)%>
                </p>
                 <%} %>
            </fieldset>
            <%} %>

Any help appreciated.

+1  A: 

Have you considered using jQuery? I use jQuery.post for my solution. Here is an example that works for me:

jQuery(document).ready(function() {

  // Dropdown or select list
  jQuery('#countryListBox').change(function(){ populateCityListBox(); });

  function populateCityListBox()
  {
    //Get ID for selected country
    var ctryID = jQuery("select#countryListBox").val();

    jQuery.post("inclyde/jquery_get_data.php", { instance: 'getCitiesByCountry', countryID: ctryID },
      function(data)
      {
          //Process data and store it in var newContent.
          // Then bind data to the div you wish to present the content
          jQuery("div.myNewText").html(newContent);

      }, "json");
  }
});

I had a hard time getting .NET Ajax working. After I discovered jQuery, things are pretty sweet :)

Steven
+1  A: 

I believe your problem with BeginForm to be that MVC always does a full page postback - at least in my experience. If you want a "partial" postback, you need to use javascript and webservices.

I'm doing exactly that using GeoIP. Here's what my page looks like:

<p>
<label for="country">Country</label>
<%= Html.DropDownList("country", new SelectList(Model.Countries, "CountryId", "Name", Model.DefaultCountry.CountryId))%>
<%= Html.ValidationMessage("country")%>
</p>

<p>
<label for="subdivision">Subregion</label>
<%= Html.DropDownList("subdivision", new SelectList(Model.Subdivisions, "SubdivisionId", "Name", Model.DefaultSubdivision.SubdivisionId)) %>
<%= Html.ValidationMessage("subdivision")%>
</p>

<script type="text/javascript">

    $('#country').change(function() {

        $('#subdivision').children().remove();

        var countryId = $("#country > option:selected").val();

        Sys.Net.WebServiceProxy.invoke   
            (   
                '/WebServices/Regions.asmx',
                "GetSubdivisions",   
                false,
                { countryId: countryId },
                addressControl_bindOptionResults   
            );
    });

    function addressControl_bindOptionResults(data)   
    {   
        for (var x = 0; x < data.length; x++) {
            $("#subdivision").append($('<option></option>').val(data[x].Id).html(data[x].Name));  
        }   
    }

</script>

My webservice looks like this. When adding a new webservice, make sure you uncomment the attribute above the class declaration:

[System.Web.Script.Services.ScriptService]

Keep in mind, your returned object has to be serializable.

[WebMethod]
        public Subdivision[] GetSubdivisions(int countryId)
        {
            if (this.repository == null)
            {
                Resolve();
            }

            List<Subdivision> subdivisions = new List<Subdivision>(repository.GetActiveSubdivisionsDto(countryId));

            return subdivisions.ToArray();
        }

Ignore some of the inner workings of my webservice. I'm using unity, Nfluent, and NHibernate for my data layer, but the basics are the same. Call the database, get your objects back, and return a list of serializable data transfer objects (mine are simply the name and Id).

Josh
A: 

The problem is the onchange = "this.form.submit();". When you submit the form by form.submit() the Ajax - Scripts of MS dont kick in. Check by placing an

<input type="submit" value="submit" />

in the form an deleting the form.submit(). The Request in the controller will then be Request.IsAjaxRequest = true.

I have no idea how you can get rid of the submit button in a nice way - I made it invisisble and clicked it by onchange via Javascript.

That was my first shot at ajax in MVC. Then I used jquery and was happy.

Malcolm Frexner