我的控制器如下......
public ActionResult Create()
{
ViewBag.Dept = (DbStudent.StudentDetails.Select(s => s.StudDept)).Distinct();
return View();
}
//
// POST: /Student/Create
[HttpPost]
public ActionResult Create(StudentDetail studentdetail)
{
try
{
// TODO: Add insert logic here I used Stored procedure for it
var query = DbStudent.StudInsert(studentdetail.StudName,
studentdetail.StudDept,
studentdetail.Mark1, studentdetail.Mark2);
return RedirectToAction("Index");
}
在视图中,我包含以下内容
<div class="editor-field">
@Html.DropDownListFor(model => model.StudDept, new SelectList(ViewBag.Dept as System.Collections.IEnumerable),
"Select Any Department")
</div>
DropDown得到填充,但选择下拉列表时我只得到空值。 请帮我 。我不知道我做错了什么
提前致谢
此致 苏里亚
答案 0 :(得分:1)
假设StudDept是StudentDetail对象的外键(因此您希望将所选值设置为StudDeptId)。这应该为您定义的集合的下拉列表,空字符串的值,标签和默认值。
试试这个:
<%= Html.DropDownListFor(model => model.StudDeptId,
new SelectList(ViewBag.Dept,
"id",
"Name",
""))%>
答案 1 :(得分:1)
我在StudentModel中创建了一个getDept属性,然后使用它填充了Drodownlist。然后使用Jquery我传递了Value it。这是代码。
public partial class StudentDetail
{
private string _StudName;
private string _StudDept;
private System.Nullable<int> _Mark1;
private System.Nullable<int> _Mark2;
private int _StudID;
public StudentDetail()
{
}
public IEnumerable<SelectListItem> getDept
{
get
{
StudentClassesDataContext objStud = new StudentClassesDataContext();
var Dept = objStud.StudentDetails.Select(x => x.StudDept).Distinct();
var deptlist = Dept.AsEnumerable();
return deptlist.Select(x => new SelectListItem
{
Value = x.ToString(),
Text = x.ToString()
});
}
}....
在控制器中我包含了以下内容..
public ActionResult studentName(string Dept)
{
var result = from s in DbStudent.StudentDetails where s.StudDept == Dept orderby s.StudName select s.StudName;
var Studname = result.AsEnumerable().Select(x => new { value = x.ToString(), text = x.ToString() });
return Json(Studname,JsonRequestBehavior.AllowGet);
}
And In View ..
<div>
Search for Another Student<br />
Department
@Html.DropDownListFor(x => x.StudDept,new SelectList(Model.getDept, "Value", "Text"),"--Select Any Dept --")
Student Name
@Html.DropDownListFor(x => x.StudName, Enumerable.Empty<SelectListItem>(), "--Select Any Student--")
<script type="text/javascript">
$('#StudDept').change(function () {
var selectedDept = $(this).val();
if (selectedDept != null && selectedDept != '') {
$.getJSON('@Url.Action("studentName")', { Dept: selectedDept }, function (names) {
var nameSelect = $('#StudName');
nameSelect.empty();
$.each(names, function (index, name) {
nameSelect.append($('<option/>', {
value: name.value,
text: name.text
}));
});
});
}
});
$('#StudName').change(function () {
var Dept = $('#StudDept').val();
var Name = $('#StudName').val();
window.location = "/Student/Search/" + Name ;
//alert("Selected Name is " + Name + " And Selected Dept is " + Dept);
});
</script>
最后,我从Dropdownlist中获得了Selected值。 希望它对别人有用...... 感谢