I wrote model class which returns a List then i pass it to view, but when the page is requested the view call the model many times and then crash the page, here’s my code please help me I am new to asp.net MVC
Model
public List<string> DoWork()
{
List<string> results = new List<string>();
using (SqlConnection con = new SqlConnection(@"Connection String Here"))
{
con.Open();
using (SqlCommand cmd = new SqlCommand(@"SELECT Column1 FROM Table1", con))
{
using (SqlDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
results.Add(rdr.GetString(0));
}
}
}
}
return results;
}
Controller
public ActionResult Index()
{
MyData data = new MyData();
return View(data);
}
View
<ul>
@for (int i = 0; i <@Model.DoWork().Count; i++)
{
<li>
@Model.DoWork()[i]
</li>
}
</ul>
The idea is that the DB layer and View layer should be separated.
This being said, you should get your DB entities in your controller action method, not in the view, and use a ViewModel pattern to spit it to the view.In your case, you have a simple view model, IEnumerable, but it can be any entity.
and in yout View, use the IEnumerable as your model, and loop though it , not calling the DB to fetch your data: