【问题标题】:To get listbox selected values in asp.net mvc3在 asp.net mvc3 中获取列表框选择的值
【发布时间】:2012-10-15 05:29:33
【问题描述】:

在 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");
        }

谁能帮忙

提前致谢

【问题讨论】:

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


    【解决方案1】:

    试试下面的

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

    从表单集合中获取 'students' 的值。具体请参考以下页面

    Pulling ListBox selected items from FormCollection

    要在 MVC 中很好地实现列表框,请阅读这篇文章。

    ASP.NET MVC Select List Example

    【讨论】:

    • 这里我需要将数据从数据库绑定到列表框
    • 请阅读上一篇文章。在那篇文章中,查看如何在 GetOptions() 方法中填充数据。通过表行枚举并填充数据,而不是填充硬编码值。
    • 在您的代码中,将以下代码替换为 ViewBag.students = new SelectList(getStudents(), "StudentID", "StudentName");然后创建一个 getStudents 方法,它从 DB 中返回 studentID 和 studentName 值。
    【解决方案2】:

    试试看:

    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; }
    }
    

    【讨论】:

    • 这里需要绑定数据库中的数据
    • 这是示例数据,数据的行为肯定是相同的,我不想在那个问题上发布非常大的数据库代码。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-13
    相关资源
    最近更新 更多