0

Here is my JavaScript:

<script type="text/javascript">
    $(function () {
        $("select#City_DDL_ID").change(function (evt) {
            if ($("select#City_DDL_ID").val() != "-1") {
                $.ajax({
                    url: "/Home/GetHotels",
                    type: 'POST',
                    dataType: "json",
                    data: { id: $("select#City_DDL_ID").val() },
                    success: function (response) {
//                        $('#Hotel_DDL_ID').attr('disabled', false);
                        $("select#Hotel_DDL_ID").replaceWith(response);
                    },
                    error: function (xhr) {
                        alert("Something went wrong, pleae try again");
                    }
                });
            }
        });
    });

Here is the Index.cshtml:

@model RoomReservation.Webb.Models.HomeViewModel

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Index</h2>

<fieldset>
    <legend>Select a city and a hotel</legend>
    <br />
    <br />
    <br />
    @Html.DropDownListFor(x=>x.City_DDL_ID, new SelectList(Model.AllCities, "Value", "Text"),"...pick a city..." )
    <br />
    <br />
    @Html.DropDownListFor(x => x.Hotel_DDL_ID, Enumerable.Empty<SelectListItem>(), "...pick a hotel...", new { disabled = "disabled"})
    <br />
    <br />
</

fieldset>

And here is the method that ajax calls:

public JsonResult GetHotels(int id) 
{
   if (id > 0)
   {
      var hotels = bl.ReturnAllHotelsInCity(id);
      return Json(hotels);
   }
   else
   {
      throw new Exception("Hotel not reachable, please try again");
   }
}

After selecting City in City_DDL_ID, my Hotel_DDL_ID disapperas. Can you help me, I am new in javasrcipt and ajax?

Here is the newset script, and still not working:

<script type="text/javascript" language="javascript">
    $('#City_DDL_ID').change(function () {
        var selectedCity = $(this).val();
        if (selectedCity != null && selectedCity != '-1') {
            $.getJSON('@Url.Action("GetHotels")', { id: selectedCity }, function (hotels) {
                var hotelsSelect = $('#Hotel_DDL_ID');
                hotelsSelect.empty();
                $.each(hotels, function (index, hotel) {
                    hotelsSelect.append($('<option/>',
                    {
                        value: hotel.Value,
                        text: hotel.Text
                    }));
                });
                $('#Hotel_DDL_ID').attr('disabled', false);
            });
        }
    });
</script>

So, what to do?

Thank you all for your help, this latest script of mine is working, I change the default browser to Chrome. Thank you all once again Cheers

P.S. Admin:How to mark question as answered?

TunAntun
  • 91
  • 10
  • With this type of problem, its best to break it down into smaller parts. Simplify you client/server into I/O params. Request the json manually to verify that the server side is taking care of its job. On the client side, start with your selectors. console.log is your friend. Check the request that is being made in the networking tab in your browser. And also be sure that you inspect the actually HTML to ensure your working with the the elements you thought you were. – Mike M Nov 01 '12 at 00:50
  • Yes, but hoew to do al that, how to call manually json response, where to write console log, and where is networking tab? Thanks – TunAntun Nov 01 '12 at 00:52
  • To call the JSON manually, just type the ajax url into your browser. Hit f12 or ctrl-shift-j to pull up developer console then the network tab will be in the menu. console.log the result of your selectors or type them in manually at the console to see what they return. – Mike M Nov 01 '12 at 01:12
  • "I change the default browser to Chrome"... And your customer/employer customers are forced to use chrome too? If it's working in Chrome then it doesn't guarantee it is working in all browsers like IE.6+ (sigh) – lboshuizen Nov 01 '12 at 01:31
  • I changed to Chrome because it has debugging tools for UI elements, not because it works only there. – TunAntun Nov 01 '12 at 09:26

2 Answers2

0

You're returning JSON from your method then replacing select#Hotel_DDL_ID with that JSON. This means that your select list is being replaced by a JSON string, which the browser wouldn't render.

$("select#Hotel_DDL_ID").replaceWith(response);

response in this case is a JSON object, not a HTML select element

You need to parse the JSON and re-populate the select list with the contents, have a look at the accepted answer on this question to see an example of that

Maybe something like this:

var html = '';
var len = response.length;
for (var i = 0; i< len; i++) {
    html += '<option value="' + response[i].Value+ '">' + response[i].Text+ '</option>';
}
$("select#Hotel_DDL_ID").html(html);

Alternatively you could modify the action to return a partial view that renders the select list as HTML, then your code would work

Community
  • 1
  • 1
Glenn Slaven
  • 33,720
  • 26
  • 113
  • 165
0

$("select#Hotel_DDL_ID"). replaceWith (response);

replaceWith says it all, it replaces the content with the new content.

If you just want to alter the content/values of [Hotel_DDL_ID] you need to evaluate (not meaning to use eval()!) the response and update the options accordingly

lboshuizen
  • 2,746
  • 17
  • 20