Reputation: 45
In asp.net Mvc3 razor, I have binded some data with dbcontext in my controller viewbag using selectlist
My controller..
public ActionResult Index()
{
ViewBag.students = new SelectList(db.StudentList, "StudentID", "StudentName");
return View();
}
Then I binded it to the ListBox using viewbag
My View..
@using (Html.BeginForm("Save", "Student"))
{
@Html.ValidationSummary(true)
<div>
@Html.ListBox("students")
<p>
<input type="submit" name="Save" id="Save" value="Save" />
</p>
</div>
}
Now, in my controller, in that Save action, I need to capture the listbox selected values I have tried the following
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Save(FormCollection formValue)
{
//need code to capture values
return View("Index");
}
Could anyone help
Thanks in advance
Upvotes: 2
Views: 5189
Reputation: 6508
Try the following
@Html.ListBox("students",ViewBag.students )
From form collection get the value of 'students'. For that please refer the following page
Pulling ListBox selected items from FormCollection
For a nice implementation of listbox in MVC please read this article.
ASP.NET MVC Select List Example
Upvotes: 3
Reputation: 7385
Try that:
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; }
}
Upvotes: 0