I have a problem,i have to retrieve the data from database and show it cshtml in a grid format….i have the data in view,but its not showing the i am geting an error this is how my code looks
BugTracker Model
namespace Gridview_BugTracker.Models
{
public class BugTracker_DataHelper
{
public static List<BugTracker_DataHelper> GetList{get;set;}
public string projectName { get; set; }
public string Description { get; set; }
public string status { get; set; }
}
------------------------------
BugTracker Controller
public ActionResult Index()
{
Gridview_BugTracker.Models.BugTracker_DataHelper model = new BugTracker_DataHelper();
SqlConnection conn = new SqlConnection(@"Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=BugTracker;Data Source=SSDEV6\SQLEXPRESS");
conn.Open();
SqlCommand dCmd = new SqlCommand("Select * from Projects", conn);
SqlDataAdapter da = new SqlDataAdapter(dCmd);
DataSet ds = new DataSet();
da.Fill(ds);
conn.Close();
for (int i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
{
model.projectName = ds.Tables[0].Rows[i]["projectName"].ToString();
model.Description = ds.Tables[0].Rows[i]["Description"].ToString();
model.status = ds.Tables[0].Rows[i]["Status"].ToString();
}
return View(model);
}
Index.Cshtml
@model IEnumerable<Gridview_BugTracker.Models.BugTracker_DataHelper>
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table>
<tr>
<th>
ProjectName
</th>
<th>
Description
</th>
<th>
Status
</th>
</tr>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.projectName)
</td>
<td>
@Html.DisplayFor(modelItem => item.Description)
</td>
<td>
@Html.DisplayFor(modelItem => item.status)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id = item.projectName }) |
@Html.ActionLink("Details", "Details", new { id = item.Description }) |
@Html.ActionLink("Delete", "Delete", new { id = item.status })
</td>
</tr>
}
I am getting this error when i execute the program
error
----------------
The model item passed into the dictionary is of type 'Gridview_BugTracker.Models.BugTracker_DataHelper',
but this dictionary requires a model item of type
'System.Collections.Generic.IEnumerable`1[Gridview_BugTracker.Models.BugTracker_DataHelper]'.
so can any one help where am i doing wrong or do i have to add any thing more…..
Because you are returning only one instance of BugTracker_DataHelpe object where the View expects a List of BugTracker_DataHelper objects. So return a list of objects to the View.
I would move the database acces code to a seprate method so that i can call it from multiple places when needed
Now call this method in your Action
Few more suggestions also
1) Add proper exception handling to the code
2) Change the
Select *toSelect specific column nameformat.3) Check for null before accessing and calling functions(
ToString()in this example) on the DataRow cell values.4) If you are simply reading the list of items, Use DataReader instead of DataSet