我在mvc 4中使用petapoco orm。当我要从数据库表中显示我的总客户列表时,它显示我未设置的对象引用和对象的实例。我的客户端表中也有一些数据或信息。为什么会出现此错误,请帮帮我... 我的索引视图是。
@model IEnumerable<FCBook.Client>
@{
ViewBag.Title = "Client list";
}
<h2>Index</h2>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table>
<tr>
<th>
@Html.DisplayNameFor(model => model.ClientName)
</th>
<th>
@Html.DisplayNameFor(model => model.ContactName)
</th>
<th>
@Html.DisplayNameFor(model => model.PhoneNo)
</th>
<th>
@Html.DisplayNameFor(model => model.Fax)
</th>
<th>
@Html.DisplayNameFor(model => model.Email)
</th>
<th>
@Html.DisplayNameFor(model => model.Address)
</th>
<th>
@Html.DisplayNameFor(model => model.City)
</th>
<th>
@Html.DisplayNameFor(model => model.PostalCode)
</th>
<th>
@Html.DisplayNameFor(model => model.Country)
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.ClientName)
</td>
<td>
@Html.DisplayFor(modelItem => item.ContactName)
</td>
<td>
@Html.DisplayFor(modelItem => item.PhoneNo)
</td>
<td>
@Html.DisplayFor(modelItem => item.Fax)
</td>
<td>
@Html.DisplayFor(modelItem => item.Email)
</td>
<td>
@Html.DisplayFor(modelItem => item.Address)
</td>
<td>
@Html.DisplayFor(modelItem => item.City)
</td>
<td>
@Html.DisplayFor(modelItem => item.PostalCode)
</td>
<td>
@Html.DisplayFor(modelItem => item.Country)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id=item.ClientId }) |
@Html.ActionLink("Details", "Details", new { id=item.ClientId }) |
@Html.ActionLink("Delete", "Delete", new { id=item.ClientId })
</td>
</tr>
}
</table>
控制器:
public ActionResult Create()
{
return View();
}
//
// POST: /Client/Create
[Httppost]
public ActionResult Create(Client collection)
{
try
{
// TODO: Add insert logic here
var db = new PetaPoco.Database("FCbook");
if (collection != null)
{
collection.Insert();
}
return RedirectToAction("Index");
}
catch
{
return View();
}
}
答案 0 :(得分:1)
Index
方法的控制器
public ActionResult Index()
{
var db = new PetaPoco.Database("FCBook");
var Cllist = db.Query<Client>("Select * from Client");
if (Cllist != null)
{
//Convert your Cllist into list of your Model i.e List<FCBook.Client>
return View(Cllist);
}
else
{
return RedirectToAction("");
}
}
答案 1 :(得分:0)
您的视图需要模型@model IEnumerable<FCBook.Client>
。但是在调用return View();
时你没有传递模型。我看到您希望通过Client
方法显示GET
列表。
而不是
public ActionResult Create()
{
return View();
}
应该是
public ActionResult Create()
{
//connect to datasource and query for Client list
model = ...
return View(model);
}
有关MVC4的详细信息,请参阅this