Partialview and passing data to layout MVC3
i want to show categories to all pages by using layout and here my way: here my model (NewsCategoriesModel)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
namespace GiaoXuKeSat.Models
{
public class NewsCategoriesModel
{
public int NewsCategoriesID { get; set; }
public string NewsCategoriesName { get; set; }
}
}
Here Partialview (_NewsCategories)
@using System.Linq;
@using System.Linq;
@model IEnumerable<GiaoXuKeSat.Models.dms_NewsCategory>
@foreach (var item in Model) {
<ul id="dmsMenuULUL">
<li>@item.NewsCategoriesName</li>
&开发者_运维百科lt;/ul>
}
and i print that partialview to layout
@Html.Partial("_NewsCategories");
but i got Object reference not set to an instance of an object. at
@foreach (var item in Model) {
You need to pass the model that your partial view needs to it. Such as.
@Html.Partial("_NewsCategories", Model.NewsItems);
If you leave the model out, you are simply passing the current view model to your partial. You can also use the ViewBag.
If you are calling a Partial from the master/layout page it is unlikely you'll have your model available on every single page. So in this case, it is better to create a controller/action that returns your news item model to a partial view and then call with...
@Html.Action("NewsCategories", "NewsController");
Which will then run the specified action and display the partial view that the action calls.
精彩评论