ClosDesign
ClosDesign

Reputation: 3924

MVC Droplist to trigger controller to get data to populate another droplist

We were able to do this with Angular, but are trying to do this with MVC using C# and Razor and possibly jQuery if need be.

What we are trying to do is, we populate a dropdown list with data already populated. (done). In our View we put an onChange event in which we then want to trigger another method in the controller so that we may get another list of items to populate the next droplist.

IN doing some VERY simple examples,we keep either getting a 404 or 500 return in our browser console and not hitting any breakpoints in Visual Studio.

This is what I have so far:

View

         <div>   @Html.DropDownListFor(model => model.Name, Model.AvailableGalaxyEventTypes, new { @id = "eventTypeName", onchange = "GetEventNames();" })
        </div>


  <script>

      function GetEventNames() {
          var url = '@Url.Action("GetData")';
          var strId = 0;
          $.ajax({
              url: url,
              type: 'GET',
              cache: false,
              data: { value: strId },

              success: function (result) {
                  alert(result);
                  console.log(result);
                  $('#result').html(result);
              }
          });
      }
      </script>

Controller

 public ActionResult GetData(string id)
    {
        return Json(new { foo = "bar", ball = "dragon" });
    }

I don't understand why we are not getting a success or anything back doing this very simple example. I should get Foo and Ball back. If we could get to the controller method, we should be able to make headway but I am getting 404 or 500 now.

Any ideas?

Upvotes: 0

Views: 79

Answers (2)

Roman
Roman

Reputation: 665

@Html.DropDownListFor(model => model.CountryId, Model.AvailableCountries)
@Html.DropDownListFor(model => model.RegionId, Model.AvailableRegions)

$("#@Html.FieldIdFor(model => model.CountryId)").change(function () {
            var selectedItem = $(this).val();
            var ddlRegions = $("#@Html.FieldIdFor(model => model.RegionId)");
            $.ajax({
                cache: false,
                type: "GET",
                url: "@(Url.RouteUrl("GetRegionsByCountryId"))",
                data: { "countryId": selectedItem, "addSelectStateItem": "true" },
            success: function (data) {
                ddlRegions.html('');
                $.each(data, function (id, option) {
                    ddlRegions.append($('<option></option>').val(option.id).html(option.name));
                });

            },
            error: function (xhr, ajaxOptions, thrownError) {
                alert('Failed to retrieve regions.');

            }
        });

And extension method that gets Id of DDL (or you can do it using JQuery or Vanilla JS):

public static string FieldIdFor<T, TResult>(this HtmlHelper<T> html, Expression<Func<T, TResult>> expression)
    {
        var id = html.ViewData.TemplateInfo.GetFullHtmlFieldId(ExpressionHelper.GetExpressionText(expression));
        // because "[" and "]" aren't replaced with "_" in GetFullHtmlFieldId
        return id.Replace('[', '_').Replace(']', '_');
    }

And method in controller:

public ActionResult GetRegionsByCountryId(string countryId)
    {
       var country = _countryService.GetCountryById(Convert.ToInt32(countryId));
        var states = _stateProvinceService.GetStateProvinces(country != null ? country.Id : 0).ToList();
        var result = (from s in states
            select new {id = s.Id, name = s.Title})
            .ToList();

        return Json(result, JsonRequestBehavior.AllowGet);
    }

Upvotes: 0

Midhun Mundayadan
Midhun Mundayadan

Reputation: 3182

your method is accepting parameter id but you are passing value as parameter in ajax request

   data: { id: strId }

or try by specifying controller name as well as action method name explicitly

  url: '@Url.Action("Foo", "SomeController")',

Upvotes: 1

Related Questions