0

I have the following question regarding the MVC and Jquery. I would like to be able to call with JQuery an action serverside and then returned result bind to a drop down list.

At this moment i do have something like that but instead of SelectList i just get back an anonymous type collection.

I have following JQuery:

<script type="text/javascript">

    (function ($) {
        $.fn.cascade = function (options) {
            var defaults = {};
            var opts = $.extend(defaults, options);

            return this.each(function () {
                $(this).change(function () {
                    var selectedValue = $(this).val();
                    var params = {};
                    params[opts.paramName] = selectedValue;
                    $.getJSON(opts.url, params, function (items) {
                        opts.childSelect.empty();
                        $.each(items, function (index, item) {
                            opts.childSelect.append(
                                $('<option/>')
                                    .attr('value', item.Id)
                                    .text(item.Name)
                            );
                        });
                    });
                });
            });
        };
    })(jQuery);

    $(function () {
        $('#Location_CountryId').cascade({
            url: '@Url.Action("Regions")',
            paramName: 'countryId',
            childSelect: $('#Location_RegionId')
        });

        $('#Location_RegionId').cascade({
            url: '@Url.Action("Cities")',
            paramName: 'regionId',
            childSelect: $('#Location_CityId')
        });
    });

</script>

Which calls this action in mvc 3:

public ActionResult Cities(int regionId)
{
    IList cities;
    using (DatingEntities context = new DatingEntities())
    {
        cities = (from c in context.cities
                   where c.RegionID == regionId
                   select new
                   {
                       Id = c.CityId,
                       Name = c.Name
                   }).ToList();
    };

    return Json(cities, JsonRequestBehavior.AllowGet);
}

My question, can i then return SelectList instead of IList and bind it properly?

Could you provide an example with my code please? I have more complex behavriou just for simpleness i posted only part of.

Thanks

4

3 回答 3

2

What about creating a partial that renders the html for the selectlist options and returing that?

_SelectList.cshtml:

@model IList<SelectListItem>

@{
  foreach (var item in Model)
  {
  <option value=@item.Value>@item.Text</option>
  }
}

And from your controller:

public ActionResult Cities(int regionId)
{
  IList<SelectListItem> cities;
  using (DatingEntities context = new DatingEntities())
  {
    cities = (from c in context.cities
              where c.RegionID == regionId
              select new SelectListItem()
              {
                Value = c.CityId,
                Text = c.Name
              }).ToList();
  };

  return PartialView("_SelectList", cities);
}

Your js can then look like this:

<script type="text/javascript">

  (function ($) {
      $.fn.cascade = function (options) {
          var defaults = {};
          var opts = $.extend(defaults, options);

          return this.each(function () {
              $(this).change(function () {
                  var selectedValue = $(this).val();
                  var params = {};
                  params[opts.paramName] = selectedValue;
                  $.get(opts.url, params, function (items) {
                    opts.childSelect.empty();
                    opts.childSelect.html(items);
                  }
              });
          });
      };
  })(jQuery);

  $(function () {
      $('#Location_CountryId').cascade({
          url: '@Url.Action("Regions")',
          paramName: 'countryId',
          childSelect: $('#Location_RegionId')
      });

      $('#Location_RegionId').cascade({
          url: '@Url.Action("Cities")',
          paramName: 'regionId',
          childSelect: $('#Location_CityId')
      });
  });

</script>

Although - I normally do something similar to your JSON code above :-)

HTH

于 2013-06-01T13:49:50.943 回答
0

How about just using some simple jQuery to iterate through the JSON object your Cities method returns. eg

<script>
    $('#Location_RegionId').change(function () {

    $.get('@Url.Action("Cities", "[ControllerName]")/' + $('#Location_RegionId').val(), function (data) {
        $('#Location_CityId').empty();
        $.each(data, function() {
                $('#Location_CityId').append($('<option />').val(this.CityId).text(this.Name));
                });
        });
   });

   $('#Location_RegionId').change();
<script/>

Assuming that your select with the regions in is called Location_RegionId and your select with cities has an id of Location_CityId.

For this to work as above it will need to be at the bottom of your view file, so the @Url.Action is rendered into the appropriate URL. Otherwise you can hard code it into a .js file and surround it with document.ready.

于 2013-06-01T15:38:25.830 回答
0

in the controller after getting list of cities convert it to a select list item as below

var list=new List<SelectListItem>(); 
list.AddRange(cities.Select(o => new SelectListItem
            {
                Text = o.Name,
                Value = o.CityId.ToString()
            }));
        }
return Json(list);
于 2013-06-03T12:46:02.017 回答