简体   繁体   中英

AJAX call on OnChange event in 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.

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.

Ok, if what you want ia a way to call a onchange event when a dropdownlist change this can be helpful:

@Html.DropDownListFor(
                        model => model.SelectedId,
                        new SelectList(ViewBag.Ids, "Id", "Name"),
                        "[All]",
                        new { onchange = "onChangeId();", @id ="municipalityDropDown" }
                        )

then you can have this javascript code and you ajax code. And here is an example of a jax code to call a action method.

function onChangeId() {
      jQuery.ajax({
            url: '@Url.Action("Action Method Name", "Controller Name")',
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify({ data: data2 }),
            success: function (result) { }
        });  
    }

Look into using a partial view. There are many links if you google ASP.Net MVC Partial View but here is one I found intestering

http://blog.stevensanderson.com/2008/10/14/partial-requests-in-aspnet-mvc/

Yes, that's right – only change is replacing:

onchange = “this.form.submit();”

with:

onchange = “$(this.form).submit();”

found it in this post

I'm not sure I completely understand what you're trying to do, but in MVC the way I would likely handle it is to chain together a couple of AJAX calls. The first updates the category ratings based on the selection. This likely returns JSON so that you can easily extract the ratings scores. The second takes the ratings scores returned by the first and calls an action that renders the chart as HTML -- ie, it renders a partial view that is returned and inserted into the proper place in the document.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM