Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AJAX call on OnChange event in MVC

Tags:

c#

asp.net-mvc

I have to make an AJAX call on the onchange event of a dropdownlist which is part of a view. On the change event i need to call the database, do some calculations display the UI and then use the calculations to populate a chart control. The UI display is in this sequence. Chart Dropdown categories list list of sub categories with rating score So as you can I need to display the categories ratings in div3 on the change event, use the ratings score to populate chart. Easily done in .NET but how to in MVC?? The only option i can think of is create user control with code behind but that defeats the purpose of using MVC. Any help is appreciated.

like image 867
user494820 Avatar asked Nov 02 '10 14:11

user494820


1 Answers

Here is a general idea how you'd implement this.

<script type="text/javascript">
    // assuming you're using jQuery
    $("#ddlAjax").change( function (event) {
        $.ajax({
            url: "Controller/GetPartialGraph/" + $(this).val(),
            data: { id = $(this).val() /* add other additional parameters */ },
            cache: false,
            type: "POST",
            dataType: "html",

            success: function (data, textStatus, XMLHttpRequest) {
                $("#divPartialView").html( data ); // HTML DOM replace
            }
        });
    });
</script>

<select id="ddlAjax">
    ... list of options
</select>


<div id="divPartialView">
    <!-- something like this in your ASP.NET View -->
    <%= Html.RenderPartial("MyPartialView", Model) %>
</div>

Here is your controller action method.

[HttpPost]
public PartialViewResult GetPartialGraph(int id /* drop down value */)
{
    // do calculations whatever you need to do
    // instantiate Model object
    var model = myBusinessLogicService.DoCalculations(id);

    return PartialView("MyPartialView", model);
}

I think this is the answer you are looking for.

like image 139
stun Avatar answered Sep 21 '22 08:09

stun