开发者

MVC View problem

<% foreach (var item in Model) { %>

        <tr>
            <td>

I get an error on my foreach statement which says Object re开发者_如何学运维ference not set to an instance of an object on Model. It just doesnt have anything at model. I have creating LinqToSql as my model...I wonder what is missing.


Off the top of my head,

public ActionResult Index()
        {
            var model = from m in Context.table
                        select m;

            return View(model);
        }

Then make sure you reference the view model in the View...

<%@ Page Title="" Language="C#" Inherits="System.Web.Mvc.ViewPage<CreditCards.ViewModels.TransactionViewModel>" %>


The reason for this error is because your model is null. Make sure your view is strongly typed to this model and that you pass a model in your controller action:

public ActionResult Foo()
{
    IEnumerable<Bar> model = FetchTheModelFromSomewhereAndMakeSureItIsNotNull();
    return View(model);
}

Now in your view you can loop use a editor/display template:

<table>
    <thead>
        <th>Id</th>
        <th>Name</th>
    </thead>
    <tbody>
    <%= Html.DisplayForModel() %>
    </tbody>
</table>

and in the corresponding display template (~/Views/Shared/DisplayTemplates/Bar.ascx):

<%@ Control 
    Language="C#" 
    Inherits="System.Web.Mvc.ViewUserControl<AppName.Models.Bar>" 
%>
<tr>
    <td><%= Html.DisplayFor(x => x.Id) %></td>
    <td><%= Html.DisplayFor(x => x.Name) %></td>
</tr>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜