2016-02-25 98 views
-1

我正在爲我們的MVC應用編輯頁面,其中包含國家和州下拉菜單。我有下拉填充。國家得到加載頁面加載,並且當一個國家被選中時,狀態列表被加載。編輯時,國家/地區列表將被填充並正確選擇。MVC5編輯的國家/州下拉列表

我的問題是如何設置要選擇的狀態。這是我到目前爲止有:

<div class="form-group col-md-4"> 
    @Html.LabelForRequired(model => model.CountryId, htmlAttributes: new {@class = "control-label"}) 
    @Html.DropDownListFor(model => model.CountryId, 
     new SelectList(ViewBag.Countries as IEnumerable, "CountryId", "CountryName"), 
     new {@class = "form-control", id = "ddlCountry"}) 
    @Html.ValidationMessageFor(model => model.CountryId, "", new {@class = "text-danger"}) 
</div> 

<div class="form-group col-md-4"> 
    @Html.LabelForRequired(model => model.State, new {@class = "control-label"}) 
    <select id="ddlState" name="@Html.NameFor(model => model.State)"></select> 
    @Html.ValidationMessageFor(model => model.State, "", new {@class = "text-danger"}) 
</div> 

這裏是我的腳本:

<script> 
    $(function() { 
     LoadStates(); 

     $("#ddlCountry").change(function() { 
      LoadStates(); 
     }); 
    }); 

    function LoadStates() { 
     var Param = { CountryId: $("#ddlCountry > option:selected").attr("value") }; 
     $.getJSON(appFolder + "Home/StateList/", Param, function (data) { 
      var items = "<option>Select State</option>"; 
      $.each(data, function (i, state) { 
       items += "<option value=" + state.StateCode + ">" + state.State + "</option>"; 
      }); 
      $("#ddlState").html(items); 
     }); 
    } 
</script> 

我一直在尋找一個例子,但還沒有找到一個。

+0

我喜歡這樣。 DotNetFiddle會持續多久? –

回答

1

雖然你可以修改成功回調的代碼,包括$("#ddlState").val(someValue);其中someValue可能是一個模型或ViewBag屬性,當前實現(手動創建<select>元素意味着你沒有得到強類型約束力,沒有得到客戶端驗證。

相反,產生在控制器中的SelectList(其可以是在一個Create視圖的情況下的空SelectList)並將其傳遞給該模型。注意其總是優選使用視圖模型,但以下可能是修改爲使用SelectLists的ViewBag屬性

視圖模型

public class ViewModel 
{ 
    [Display(Name = "Country")] 
    [Required(ErrorMessage = "Please select a country")] 
    public int? CountryID { get; set; } 
    [Display(Name = "State")] 
    [Required(ErrorMessage = "Please select a state")] 
    public int? StateID { get; set; } 
    .... // other properties needed for the view 
    public IEnumerable<SelectListItem> CountryList { get; set; } 
    public IEnumerable<SelectListItem> StateList { get; set; } 
} 

控制器

private void ConfigureViewModel(ViewModel model) 
{ 
    var countries = db.Countries; 
    model.CountryList = new SelectList(countries, "CountryId", "CountryName"); 
    if (model.StateID.HasValue) 
    { 
     var states = db.States.Where(s => s.CountryId == model.StateID.Value); 
     model.StateList = new SelectList(states, "StateId", "StateName"); 
    } 
    else 
    { 
     model.StateList = new SelectList(Enumerable.Empty<SelectListItem>()); 
    } 
} 

public ActionResult Create() 
{ 
    ViewModel model = new ViewModel(); 
    ConfigureViewModel(model); 
    return View(model); 
} 
[HttpPost] 
public ActionResult Create(ViewModel model) 
{ 
    if (!ModelState.IsValid) 
    { 
     ConfigureViewModel(model); 
     return View(model); 
    } 
    // Initialize data model and set its properties based on view model 
    // Save data model and redirect 
} 
public ActionResult Edit(int ID) 
{ 
    // Get data model based on ID 
    ViewModel model = new ViewModel(); 
    // Set properties based on data model 
    ConfigureViewModel(model); 
    return View(model); 
} 
[HttpPost] 
public ActionResult Edit(ViewModel model) 
{ 
    if (!ModelState.IsValid) 
    { 
     ConfigureViewModel(model); 
     return View(model); 
    } 
    // Get data model and set its properties based on view model 
    // Save data model and redirect 
} 

,並在視圖

@Html.DropDownListFor(m => m.CountryID, Model.CountryList, new {@class = "form-control"}) 
.... 
@Html.DropDownListFor(m => m.StateID, Model.StateList, new {@class = "form-control"}) 

var url = '@Url.Action("StateList", "Home")'; // don't hard code your url's 
var states = $('StateID'); // cache it 
$('#CountryID').change(function() { 
    states.empty(); 
    $.getJSON(url, { CountryId: $(this).val() }, function(data) { // use $(this) 
    if (!data) { 
     return; 
    } 
    // add empty option with value="" so you get client side validation 
    states.append($('<option></option>').val('').text('Please select')); 
    $.each(data, function(index, item) { 
     subLocalities.append($('<option></option>').val(item.StateCode).text(item.State)); 
    }); 
});