2014-05-09 5 views
0

국가 및 주와 같은 두 개의 드롭 다운 목록이 있습니다. 국가 값에 따라 상태를로드해야합니다.다른 드롭 다운 값을 기준으로 드롭 다운 값을로드하는 방법

나는 ajax 호출을 만들고 countrydropdown의 change 이벤트를 실행한다.

지금 내 질문은 국가 드롭 다운 값에

Model 

public SelectList statename { get; set; } 
public string selectedvalue { get; set; } 


Controller 

[HttpPost] 
     public ActionResult form(displayModel disp) 
     { 
      var display = new displayModel(); 
      List<string> state = new List<string>(); 
      if (disp.selectedvalue == "India") 
      { 
       state.Add("TN"); 
       state.Add("KL"); 
       state.Add("UP"); 
      } 
      display.statename = new SelectList(state, "--select--"); 
      return View(display); 
     } 
View 

@Html.LabelFor(model=>model.statename) 
@Html.DropDownListFor(model => model.statename, Model.statename, new { id="dropstate"}) 

$("#dropdown1").change(function() { 
      $.ajax({ 
       url: "/Home/form", 
       type: "post", 
       data: { 
        selectedvalue: $("#dropdown1 option:selected").text() 
       }, 
       success: function (data) { 
        alert(data); 

       } 
      }); 
     }); 

답변

0

당신은

Controller: 

public JsonResult GetStateList() { 
    var list = new List<ListItem>() { 
    new ListItem() { Value = "1", Text = "VA" }, 
    new ListItem() { Value = "2", Text = "MD" }, 
    new ListItem() { Value = "3", Text = "DC" } 
    }; 
    return this.Json(list); 
} 


$(function() { 
$("#dropdown1").change(function() { 
    $.getJSON("/Home/GetStateList", { Id: $("#dropdown1 option:selected").val() }, 
     function(fooList) { 
      $("#state").empty(); 
      $.each(fooList, function(i, foo) { 
       $("#state").append(""+ foo.Value + ""); 
      }); 
     }); 
    }); 
}); 
0

당신은 컨트롤러에 selectedCountryId를 보낼 수있는 드롭 다운에서 결과를 채우는 다음 선택한 ID를 대신하여 JSON을 반환 할 것이다 컨트롤러 메소드를 호출하기 위해이 같은 아약스 전화를 사용할 수 있습니다이고 State 목록 항목을 JSON 데이터로 채울 수 있습니다.

아약스 코드 :

$('#dropdown1').change(function() { 
     var selectedCountryId = $(this).val(); 
     $.getJSON('@Url.Action("form")', { countryId: selectedCountryId }, function (data) { 
      var select = $('#dropstate'); 
      select.empty(); 
      $.each(data, function (index, sta) { 
       select.append(
        $('<option/>') 
         .attr('value', sta.Value) 
         .text(sta.Text) 
       ); 
      });     
     }); 
    }); 

컨트롤러 코드 :

public ActionResult form(int countryId) 
    { 
     //Here you can check the countryId & if any logic you want 
     //Or Else you can call the service method here and opcode StateListItems, 
     //If so then you have make a little change to the below JSON data   
     var stateList = new List<StateItem>() 
         { 
          new ListItem() { Value = "1", Text = "AndraPradesh" }, 
          new ListItem() { Value = "2", Text = "Karnataka" }, 
          new ListItem() { Value = "3", Text = "TamilNadu" } 
         }; 
     var rows = service.ToArray(); 
     return Json(rows, JsonRequestBehavior.AllowGet); 
    } 
관련 문제