Sending a list to the view
I'm working on a page on my little project where I want to list all users in my database to a page.
At the moment I'm at the select statement, but I dont know how to pass it to the view:
public ActionResult Index开发者_开发技巧()
{
SqlConnection connection = new ...
connection.Open();
SqlCommand command = new SqlCommand("SELECT * FROM users", connection);
???
How do I pass it to the view and how do I list all the items? Any suggestions?
What you need to do is populate ViewData.Model with your list of users. So try this:
//Same code as you already have...
SqlDataAdapter da = new SqlDataAdapter(command);
DataTable dt = new DataTable();
da.Fill(dt);
List<CustomUserObject> userList = new List<CustomUserObject>();
foreach (DataRow dr in dt.Rows)
{
//Create a class to house your user object before this next part will work.
CustomUserObject cuo = new CustomUserObject { FirstName = dt.Rows[0]["FirstName"].ToString(), LastName = dt.Rows[0]["LastName"].ToString(), etc... };
userList.Add(cuo);
}
ViewData.Model = userList;
return View();
Now, assuming you haven't created the view for your action method yet, right click somewhere inside the action method (in Visual Studio) and create view. Make sure the view has Strongly Typed View selected. Set the view model to IEnumerable<CustomUserObject>
. Now when you are in the view you would reference your model like this.
<% foreach (CustomUserObject cuo in Model)
{ %>
<%: Html.TextBoxFor(cuo.FirstName) %>
<!-- More controls for all properties on your user object... -->
<% } %>
精彩评论