AJAX调用MVC中的OnChange事件

use*_*820 7 c# asp.net-mvc

我必须在下拉列表的onchange事件上进行AJAX调用,这是视图的一部分.在更改事件上,我需要调用数据库,执行一些计算显示UI,然后使用计算来填充图表控件.UI显示按此顺序显示.图表下拉类别列表具有评级分数的子类别列表因此,您可以在更改事件中显示div3中的类别评级,使用评级分数填充图表.在.NET中轻松完成但是如何在MVC中完成?我能想到的唯一选择是使用代码创建用户控件,但这会破坏使用MVC的目的.任何帮助表示赞赏.

stu*_*tun 9

以下是您如何实现这一点的一般概念.

<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>
Run Code Online (Sandbox Code Playgroud)

这是你的控制器动作方法.

[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);
}
Run Code Online (Sandbox Code Playgroud)

我想这就是你要找的答案.


Joh*_*ock 1

考虑使用局部视图。如果你用 google 搜索 ASP.Net MVC Partial View 有很多链接,但这里是我发现有趣的一个

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