2

在 asp.net Mvc3 razor 中,我使用 selectlist 在我的控制器视图包中将一些数据与 dbcontext 绑定

我的控制器..

public ActionResult Index()
        {
            ViewBag.students = new SelectList(db.StudentList, "StudentID", "StudentName");
            return View();
        } 

然后我使用 viewbag 将它绑定到 ListBox

我的观点..

@using (Html.BeginForm("Save", "Student"))
{    
    @Html.ValidationSummary(true)
    <div>
     @Html.ListBox("students")
    <p>
        <input type="submit" name="Save" id="Save" value="Save" />
    </p>
    </div>
}

现在,在我的控制器中,在该保存操作中,我需要捕获列表框选择的值,我尝试了以下操作

[AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Save(FormCollection formValue) 
        {
            //need code to capture values                
            return View("Index");
        }

谁能帮忙

提前致谢

4

2 回答 2

3

尝试以下

 @Html.ListBox("students",ViewBag.students )

从表单集合中获取“学生”的值。为此,请参阅以下页面

从 FormCollection 中提取 ListBox 选定项

对于 MVC 中列表框的一个很好的实现,请阅读这篇文章。

ASP.NET MVC 选择列表示例

于 2012-10-15T05:45:49.740 回答
0

试试看:

public class StudentController : Controller
{
    //
    // GET: /Student/

    public ActionResult Index()
    {
        var studentList = new List<Student>
                              {
                                  new Student {StudentID = 1, StudentName = "StudentName1"},
                                  new Student {StudentID = 2, StudentName = "StudentName2"},
                                  new Student {StudentID = 3, StudentName = "StudentName3"},
                                  new Student {StudentID = 4, StudentName = "StudentName4"}
                              };

        ViewBag.students = new SelectList(studentList, "StudentID", "StudentName");
        return View();
    } 

    [HttpPost]
    public ActionResult Save(String[] students)
    {
        return View();
    }

}

public class Student
{
    public int StudentID { get; set; }
    public string StudentName { get; set; }
}
于 2012-10-15T05:44:28.977 回答