我还是MVC的新手并且正在努力解决它。我需要得到"名称"我的分区表列成一个下拉列表,可以从不同的区域中选择。最终游戏是用户将从下拉列表中选择一个区域,然后被定向到一个页面,其中将显示所选区域的学校列表(在不同的表中)(我认为这将是对数据库的查询使用下拉列表中给出的值)。基本上我到目前为止所做的是:
创建MVC应用程序。
创建实体框架模型。
我一步一步地复制这些教程告诉我要做的事情,但是我得到了不同的结果。我的下拉列表给了我这个结果:
我需要帮助解决可能出现问题的原因以及数据未显示在我的下拉列表中的原因。
答案 0 :(得分:2)
尝试我相信您使用的是错误的SelectList构造函数。假设您希望下拉列表的值为" leaID"属性
@Html.DropDownList("myList", new SelectList(ViewBag.districts, "leaId", "name")
然而,我会以另一种方式接近它,这将保持它主要是强类型:
public class DistrictViewModel
{
public string SelectedDistrictId { get; set; }
public IEnumerable<SelectListItem> Districts { get; set; }
}
动作:
public ActionResult Index()
{
var viewModel = new DistrictViewModel()
{
Districts = new SelectList(db.Districts.ToList(), "leaID", "name")
}
return View(viewModel);
}
CSHTML:
@model DistrictViewModel
@Html.DropDownListFor(m => m.SelectedDistrictId, Model.Districts)
答案 1 :(得分:0)
以下是我使用ajax
对您的评论的回答//Model
public class DistrictViewModel
{
public string name {get;set;}
public SelectList District {get;set;}
public int SelectedDistrict {get;set}
}
//Controller
public class DistrictController : Controller
{
KUDEREntities db = new KUDEREntities();
public ActionResult Index()
{
var model = new DistrictViewModel();
model.Districts = db.Districts.ToList();
model.SelectedDistrict=0;
return view(model);
}
[HttpPost]
public ActionResult Search(int id)
{
//do the search with the id of the selected district
var data = db.Districts.Where(m=>m.leaId = id).FirstorDefault();//this would return the whole object.
return Json(data, JsonRequestBehavior.AllowGet);
}
}
//Index View
@Model DistrictViewModel
<div>
//with this your selector would be "#SelectedDistrict"
@Html.DropDownListFor(model=>model.SelectedDistrict, new SelectList(Model.Districts,"leaId","name",Model.SelectedDistrict), new {@class=""})
//with this your selector would be "#myList"
//@Html.DropDownList("myList", new SelectList(ViewBag.districts, "leaId", "name", Model.SelectedDistrict)
</div>
<script>
$(document).ready(function(){
//when you want to search for the id selected, you just need to call the Search function below
function Search() {
//... now you have the value of the selecteditem
var parameters = { id: $("#SelectedDistrict").val() };
$.ajax({
type: 'post',
url: '@Url.Action("Search", "District")',
cache: false,
contentType: "application/json; charset=utf-8",
dataType: "html",
async: true,
data: JSON.stringify(parameters),
success: function (data) {
//...do whatever with the data
},
failure: function (msg) {
//... show a message of error
}
});
}
});
</script>