为什么我没有在提交事件上获得DropDownList值

时间:2015-04-17 14:38:47

标签: c# .net asp.net-mvc asp.net-mvc-4

在我的MVC4项目中,我无法在编辑控制器上获取我的DropDownList数据。 我的UI语法如下:

<div class="form-group">
    @Html.HiddenFor(model => model.School.SchoolID)
    @Html.LabelFor(model => model.School.SchoolName, new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.EditorFor(model => model.School.SchoolName)
        @Html.ValidationMessageFor(model => model.School.SchoolName)
    </div>
</div>       

<div class="form-group">
    @Html.HiddenFor(model => model.StudentCLass.ID)
    @Html.LabelFor(model => model.StudentCLass.ClassName, new { @class = "control-label col-md-2" })
    <div class="col-md-10"> 
        @Html.DropDownListFor(model => model.StudentCLass.ID, @ViewBag.StudentCLassList as SelectList,"Select Class")
        @Html.ValidationMessageFor(model => model.StudentCLass.ID)
    </div>
</div>


<div class="form-group">
    <div class="col-md-offset-2 col-md-10">
        <input type="submit" value="Save" class="btn btn-default" />
    </div>
</div>

要填充DropDownList,请使用以下语法:

public ActionResult Edit(int Id)
{
    using (DB = new StudentContext())
    {
        var result = DB.Students.FirstOrDefault(c => c.ID == Id);                
        ViewBag.StudentCLassList = new SelectList(DB.StudentClasses
               .Select(sc => new ViewModelClass 
               { 
                   ID = sc.ID, 
                   ClassName = sc.ClassName 
               }).ToList(), "ID", "ClassName"); 

         return View(StudentInfo(result));
     }
 }

点击提交按钮后,我的控制器操作无法获得DropDownList值。

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(ViewModel.ViewModelStudents student)
{    
    var tempResult = student.StudentCLass.ID;    
    //return RedirectToAction("Index");

//返回查看(学生);     }

模型结构

public partial class StudentClass
{
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
    public StudentClass()
    {
        Students = new HashSet<Student>();
    }

    public int ID { get; set; }

    [StringLength(100)]
    public string ClassName { get; set; }

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<Student> Students { get; set; }
}

2 个答案:

答案 0 :(得分:2)

MVC Doen将DropDown列表发布回Controller,您将不得不在POST方法中再次填充下拉列表:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(ViewModel.ViewModelStudents student)
{    
    var tempResult = student.StudentCLass.ID;

ViewBag.StudentCLassList = new SelectList(DB.StudentClasses
               .Select(sc => new ViewModelClass 
               { 
                   ID = sc.ID, 
                   ClassName = sc.ClassName 
               }).ToList(), "ID", "ClassName"); 

    return RedirectToAction("Index");
}

您可以在函数中编写下拉列表代码,如果您不想从数据库中读取此下拉列表,则可以将其保存到Session[]

    public void PopulateDropDownList(){

var items = Session["MyDropDown"] != null ? (SelectList)Session["MyDropDown"] : null;
if(items ! null) {ViewBag.StudentCLassList; return;}

        items = new SelectList(DB.StudentClasses
                       .Select(sc => new ViewModelClass 
                       { 
                           ID = sc.ID, 
                           ClassName = sc.ClassName 
                       }).ToList(), "ID", "ClassName"); 

Session["MyDropDown"] = ViewBag.StudentCLassList = items;

    }

注意:如果您将DropDown列表保存在Session中,则无法将其写入ViewBag,但您可以直接在View中访问它。

在Controller中调用此方法:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(ViewModel.ViewModelStudents student)
{    
    var tempResult = student.StudentCLass.ID;

    PopulateDropDownList(); 

    return RedirectToAction("Index");
}

修改

我不明白你是说你想要选择DropDown,但你Redirecting指的是`索引&#39;。

如果你这样做:

return View(student);

而不是

return RedirectToAction("Index");

return RedirectToAction("Index");会将您重定向到“索引”页面,刷新您的网页。

编辑2:

我刚注意到你有

@Html.HiddenFor(model => model.StudentCLass.ID)

MVC将此隐藏的值发布到控制器。尝试删除它,

问题是你有两个具有相同id

的控件
@Html.DropDownListFor(model => model.StudentCLass.ID

AND 

@Html.HiddenFor(model => model.StudentCLass.ID)

答案 1 :(得分:0)

我想你想要这样的东西:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(ViewModel.ViewModelStudents student)
{
    if (ModelState.IsValid)
    {
         // save changes and redirect

         return RedirectToAction("Index");
    }
    else
    {
        using (DB = new StudentContext())
        {
            ViewBag.StudentCLassList = new SelectList(DB.StudentClasses.ToList(), "ID", "ClassName");         
        }

        return View(student);
    }
}

该框架将负责跨请求保留选定的值。