Search code examples
jqueryasp.net-mvc-4webgrid

Trying to Display Dynamic WebGrids Based On DropDownList Selection - ASP.Net MVC4


My Index view has a populated DropDownList of ClientIDs. My intention is to dynamically display a WebGrid of email addresses when one of the ClientIDs is chosen. Using the following jQuery code, I am successfully going to a controller action called PopulateEmailAddressUI.

jQuery(document).ready(function () {
    $("#MeditechDropDown").change(function () {
        var id = $(this).find(":selected").val()
        var clientID = { "clientID": id }
        $.ajax({
            url: "/Home/PopulateEmailAddressUI",
            data: JSON.stringify(clientID), // Send value of the drop down change of option
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
            success: function (response) {
                $('#gridContent').load()
            }
        });
    });
});

My controller action looks like:

[HttpPost]
public ActionResult PopulateEmailAddressUI(string clientID)
{
    _clientModel = InitialiseBarClientsModel();

    _clientModel.FindEmailAddresses(from client in eFormsDB.BAR_Clients where client.ClientId == clientID select client);

    return PartialView("_EmailAddressGrid", _clientModel);
}

My _EmailAddressGrid partial view looks like:

@model BarClients.Models.BarClientsViewModel

@{
    var grid = new WebGrid(Model.EmailAddressesOfChosenClient, ajaxUpdateContainerId: "gridContent");
}

    div id="gridContent"
    @grid.GetHtml()  
    /div (arrows omitted).

The trouble I am having with this approach is no WebGrid ever shows up. If I look at page source, all I see is the Index view with ClientIDs but no element with div id of gridContent.

What change do I need to make my approach so that I can have different WebGrids dynamically display every time a ClientID is selected from the DropDownList?

Many thanks.


Solution

  • Your code is right, but you've forgotten to use the response. Check this code:

     success: function (response) {
       $('#gridContent').load()
     }
    

    The line inside the function is doing nothing... and you're not using the response.

    Replace it with this:

     success: function(html) {
       $("#gridContent").html(html);
     }
    

    You can use this code, or any of the DOM Replacement or DOM Insertion, Inside or whatever.

    It's also advisable to include the parameter dataType:'html' to the jquery ajax call, to indicate that you're expecting html as response. (NOTE: I've called the function parameter html to indicate the raw response is html, but you can give it the name you like).

    You should also add an error handler to your ajax invocation. You can do it globally with $.ajaxSetup(). In this way, if something goes wrong with the communications or the server, you'll get some feedback.