级联下拉列表与Json固定的Guid Id
本文关键字:Guid Id 下拉列表 Json 级联 | 更新日期: 2023-09-27 18:02:42
大家好,我需要修复一个级联下拉列表与Guid Id工作…使用Int Id可以正常工作…但是我需要在我的表上使用Guid Id。
当我将类型更改为Guid(在我的模型和数据库上)…它不会填充下拉列表
请帮忙解决这个问题
I got this:
控制器 public JsonResult GetCountries()
{
return Json(countries.GetAll().ToList(), JsonRequestBehavior.AllowGet);
}
public JsonResult GetStatesByCountryId(string countryId)
{
//I know, I have to convert to Guid here... the problem is in the first dropdownlist
int Id = Convert.ToInt32(countryId);
var states = from s in state.GetAll() where s.CountryId == Id select s;
return Json(states);
}
<<p> 视图/strong> <div>
@Html.DropDownList("dropdownCountry", new SelectList(string.Empty, "Value", "Text"), "Please select a country", new { @style = "width:250px;" })
</div>
<div style="margin-top:50px;">
@Html.DropDownList("dropdownState", new SelectList(string.Empty, "Value", "Text"), "Please select a state", new { @style = "width:250px;" })
</div>
</div>
<!-- jQuery -->
<script src="~/Assets/vendors/jquery/dist/jquery.min.js"></script>
<!-- Bootstrap -->
<script src="~/Assets/vendors/bootstrap/dist/js/bootstrap.min.js"></script>
<script type="text/javascript">
$(function () {
$.ajax({
type: "GET",
url: "/Home/getcountries",
datatype: "Json",
success: function (data) {
$.each(data, function (index, value) {
//I think the problem is here it doesn't read Guid Numbers...when CountryId is a Guid
$('#dropdownCountry').append('<option value="' + value.CountryId + '">' + value.CountryName + '</option>');
});
}
});
$('#dropdownCountry').change(function () {
$('#dropdownState').empty();
$.ajax({
type: "POST",
url: "/Home/GetStatesByCountryId",
datatype: "Json",
data: { countryId: $('#dropdownCountry').val() },
success: function (data) {
$.each(data, function (index, value) {
$('#dropdownState').append('<option value="' + value.Id + '">' + value.StateName + '</option>');
});
}
});
});
});
</script>
如果将实体模型/db中的Id类型更改为Guid,则下面一行将失败
public JsonResult GetStatesByCountryId(string countryId)
{
int Id = Convert.ToInt32(countryId);
}
转换。ToInt32需要一个可以转换为有效int的对象(例如:"123")。但是Guid就像"49e17a97-88ce-4acc-8aba-ae0c8740fd5d"
一样,不能转换为int。所以只要使用Guid作为参数。
public JsonResult GetStatesByCountryId(Guid countryId)
{
var states = (from s in state.GetAll() where s.CountryId == countryId
select s).ToList();
return Json(states, JsonRequestBehavior.AllowGet);
}
假设state.GetAll
方法返回一个项目集合,其中它具有Guid类型的CountryId属性。(并且状态id也是Guids)