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 th
Yes, that’s right – only change is replacing:
onchange = “this.form.submit();”
with:
onchange = “$(this.form).submit();”
found it in this post
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) { }
});
}
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 -- i.e., it renders a partial view that is returned and inserted into the proper place in the document.
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/