这是我在图像 问题级联下拉列表,产生下拉不发帖选中的值给服务器
代码工作正常的观点,但...
当我提交表单,它只发送第一个下拉列表的值(我在浏览器网络上收到的参数时进行了检查),当我查看页面源时,它不显示使用ajax函数生成的生成选项。
这里是我的代码
行动产生我的第一个下拉列表
public ActionResult TwoDropDownList()
{
HotelContext H = new HotelContext();
ViewBag.DropDownListOne = new SelectList(H.Continent.ToList(), "Id", "Name");
return View();
}
行动返回的第二个下拉列表数据
[HttpPost]
public JsonResult UpdateCountryDropDownList(int ContinentId)
{
HotelContext H = new HotelContext();
List<SelectListItem> CountryNames = new List<SelectListItem>();
List<Country> Co = H.Country.Where(x => x.ContinentId == ContinentId).ToList();
Co.ForEach(x =>
{
CountryNames.Add(new SelectListItem { Text = x.Name, Value = x.Id.ToString() });
});
return Json(CountryNames , JsonRequestBehavior.AllowGet);
}
我的Ajax调用JSON
@model Hotel.Models.Continent
<script>
$(document).ready(function() {
$("#Name").change(function() {
var ContinentoId = $(this).val();
$.ajax({
type: "POST",
dataType: "json",
data: { ContinentId: ContinentoId },
url: '@Url.Action("UpdateCountryDropDownList","Home")',
success: function (result) {
var Country = "<select id='ddlCountry'>";
Country = Country + '<option value="">--Select--</option>';
for (var i = 0; i < result.length; i++) {
Country = Country + '<option value=' + result[i].Value + '>' + result[i].Text + '</option>';
}
Country = Country + '</select>';
$('#Countries').html(Country);
},
error: function (xhr, ajaxOptions, thrownError) {
console.log(arguments)
}
});
});
})
</script>
我查看
@using(Html.BeginForm()){
SelectList se = ViewBag.DropDownListOne;
@Html.DropDownListFor(x=>x.Name,se,"--Select--")
<div id ="Countries">
@Html.DropDownList("ddlCountry",new List<SelectListItem>(),"--Select--")
</div>
<input type="submit" value="submit" style="margin-top:100px;" />
}
HTTPPost行动
[HttpPost]
public string TwoDropDownList(string Name, string ddlCountry)
{
if (string.IsNullOrEmpty(Name) || string.IsNullOrEmpty(ddlCountry))
{
return ("you must select Both");
}
else
return ("everything is working fine");
}
谢谢你正常工作 –
除了这些错误之外,你所做的其余工作非常糟糕 - 不使用模型,使用ViewBag,没有强类型绑定,没有客户端验证和弱服务器端验证。我建议你学习代码也推荐你在[DotNetFiddle](https://dotnetfiddle.net/1bPZym)中学习代码。 –