I have the following ASP.NET MVC .cshtml file in which I do the following:
Grab the Name & Id values from MyObject and create a DropDownList out of them, when the user selects an item in the Drop Down box I attempt to use AJAX to call TheMethodToCall which is a method in TheController, and attempt to display the text result returned by TheMethodTocall.
@model List<MyWebApp.Models.MyObject>
@if (Model.Count > 0)
{
using (Html.BeginForm())
{
<div class="input-group mb-3">
@Html.DropDownList("SelectFromDropdownList", Model.Select(i => new SelectListItem()
{
Text = i.Name,
Value = i.Id
}), "This is the default DropDownList option", new { @class="custom-select", @id="mydropdownid"})
<script>
$(function(){
$('#SelectFromDropdownList').change(function () {
var typeFeed = $(this).val();
// Perform AJAX call
$.get("@Url.Action("TheMethodToCall", "TheController")", { TypeFeed: typeFeed }, function (result){
@Html.DisplayText(result);
});
});
});
</script>
</div>
}
}
I'm having a couple of issues, please help! Here they are:
- I have put my Visual Studio debugger breakpoint in the
TheMethodToCallmethod, but it does not get hit when the user selects an item from theDropDownList. - Is this the correct way of displaying the
resulttext which is returned formTheMethodToCall?
Update
I appreciate the answers so far, but I'm setting a breakpoint in this method, but it is still not being called. I did change $('#SelectFromDropdownList').change(function () to $('#mydropdownid').change(function (). Is there anything else to do?
[WebMethod()]
public static string TheMethodToCall()
{
return "This is a test";
}
new { id="mydropdownid" }which generates<select id="mydropdownid"... >` so you do not have an element withid="SelectFromDropdownList"- therefore the script needs to be$('#mydropdownid').change(function () {@Html.DisplayText(result);will not work. To add the result to the DOM you need$(someElement).html(result)[WebMethod()]? And it should bepublic ActionResult TheMethodToCall() { return Content("This is a test"); }{ TypeFeed: typeFeed }but your function doesn't accept any parameters. For now while you're learning, don't send any data. It just complicates things.TheMethodToCalldoes not get called (breakpoint not hit inside of it). Could it be that i'm missing the AJAX library? Or that@Url.Actionis the wrong method to be using? For the 2nd parameter inUrl.Action, if I had a controller namedHouseController, would I putHouseorHouseControlleras this method's 2nd parameter?