Reputation: 511
Ok, so I have seen a lot of similar questions, but unfortunalety I can't figure out how to access a list of users from db in the View. I get a System.NullReferenceException. Can one of you experts see what I am doing wrong?
Model
public class MyModel
{
[Key]
public int Id { get; set; }
[Display(Name = "Name")]
public string Name { get; set; }
public bool TriggerOnLoad { get; set; }
public string TriggerOnLoadMessage { get; set; }
public string EmployeeNumber { get; set; }
public IEnumerable<User> Users { get; set; }
public List<MyModel> GetAllUsers()
{
var queryString = "SELECT Name FROM Users";
var adapter = new SqlDataAdapter(queryString, System.Configuration.ConfigurationManager.ConnectionStrings["SQLConn"].ConnectionString);
var current = new DataSet();
adapter.Fill(current, "Name");
return (from DataRow item in current.Tables[0].Rows
select new MyModel()
{
Name = Convert.ToString(item["Name"]),
}).ToList();
}
Controller
public ActionResult GetUser()
{
var model = new MyModel();
_db.GetAllUsers();
return View(model);
}
View
@model ModelName.Models.MyModel
--HTMLCode--
@foreach (var item in Model.Users) <-- Exception.
{
<tr>
<td>@Html.DisplayFor(modelItem => item.Name)</td>
</tr>
}
What am I forgetting?
Upvotes: 0
Views: 138
Reputation: 1151
Your problem is that you are getting the users, but you are not passing the users to the view, instead, you pass an empty model.
A better approach would be to create a ViewModel with all the properties you need in the view.
Let's say your view model looks something like this:
ViewModel:
class YourViewModel
{
public string Name { get; set; }
public bool TriggerOnLoad { get; set; }
public IEnumerable<User> Users { get; set; }
}
After creating your ViewModel what you need to do is that you need to create an instance of the ViewModel in your Controller and fill it with data and then pass the ViewModel to the View. In your case it would look something like this:
Action:
public ActionResult RandomAction()
{
YourViewModel vm = new YourViewModel()
{
Users = _db.GetAllUsers(),
Name = "Random Name",
TriggerOnLoad = true
};
return View(vm);
}
Later on, if you decide you need some extra properties you need to work with in your view, you just add them to your ViewModel and continue on.
Upvotes: 2
Reputation: 55248
Pass users like this. You are not passing the users to View
public ActionResult GetUser()
{
var model = new MyModel();
var users = _db.GetAllUsers();
return View(users);
}
Then in View
@model List<MyModel>
@foreach (var item in Model) //foreach through the list
{
<tr>
<td>@Html.DisplayFor(model => item.Name)</td>
</tr>
}
Upvotes: 1