我的Project模型类就像这样
public class Project
{
[Key]
public int Id { get; set; }
[Required(ErrorMessageResourceType = typeof(Resources.Resources),
ErrorMessageResourceName = "EmptyProjectName")]
[Display(Name = "ProjectName", ResourceType = typeof(Resources.Resources))]
public string Name { get; set; }
[ForeignKey("Country")]
[Required(ErrorMessageResourceType = typeof(Resources.Resources),
ErrorMessageResourceName = "EmptyCountry")]
[Display(Name = "Country", ResourceType = typeof(Resources.Resources))]
public int CountryId { get; set; }
[ForeignKey("Province")]
[Required(ErrorMessageResourceType = typeof(Resources.Resources),
ErrorMessageResourceName = "EmptyProvince")]
[Display(Name = "Province", ResourceType = typeof(Resources.Resources))]
public int ProvinceId { get; set; }
public Country Country { get; set; }
public Province Province { get; set; }
}
我的创建视图就像这样
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>Project</legend>
<div class="editor-label">
@Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.CountryId)
</div>
<div class="editor-field">
@Html.DropDownList("CountryId", string.Format("--- {0} {1} ---", @Resources.Resources.Select, @Resources.Resources.Country))
@Html.ValidationMessageFor(model => model.CountryId)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.ProvinceId)
</div>
<div class="editor-field">
@Html.DropDownList("ProvinceId", string.Format("--- {0} {1} ---", @Resources.Resources.Select, @Resources.Resources.Province))
@Html.ValidationMessageFor(model => model.ProvinceId)
</div>
<p>
<input type="submit" value=@Resources.Resources.Create />
</p>
</fieldset>
}
这里我需要加载“国家/地区”中存在的“省份”。即选择国家时,所选国家/地区的省份需要加载到省内。
对于这种情况,我添加了这样的脚本。
<script type="text/javascript">
$(document).ready(function () {
//Dropdownlist Selectedchange event
$("#CountryId").change(function () {
debugger;
$("#ProvinceId").empty();
$.ajax({
type: 'POST',
url: "ProjectController/GetProvincesForCountry/", /
dataType: 'json',
data: { countryId: $("#CountryId").val() },
success: function (provinces) {
$.each(data, function (i) {
var optionhtml = '<option value="' +
data[i].Id + '">' + data[i].Name + '</option>';
$("#ProvinceId").append(optionhtml);
});
},
error: function (ex) {
debugger;
alert( ex.toString());
}
});
return false;
})
});
</script>
这是我在控制器中的方法
public JsonResult GetProvincesForCountry(int countryId)
{
return Json(db.Provinces.Where(x => x.CountryId.Equals(countryId)).ToList());
}
但是当我从下拉消息中选择国家时,会出现[对象对象]
这是我的国家,省模型类
public class Country
{
public int Id { get; set; }
public string Name { get; set; }
}
public class Province
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
[ForeignKey("Country")]
public int CountryId { get; set; }
public Country Country { get; set; }
}