本文转自:http://www.nopchina.net/post/nopchina-teach-newscategory.html

nopcommerce的新闻模块一直都没有新闻类别,但是很多情况下都会使用到类别,怎么办呢,自己动手吧。

1、首先创建新闻类别表,脚本如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
CREATE TABLE [dbo].[NewsCategory](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [Name] [nvarchar](400) NOT NULL,
    [Description] [nvarchar](max) NOT NULL,
    [ParentCategoryId] [int] NOT NULL,
    [Published] [bit] NOT NULL,
    [Deleted] [bit] NOT NULL,
    [DisplayOrder] [int] NOT NULL,
    [CreatedOn] [datetime] NOT NULL,
    [UpdatedOn] [datetime] NOT NULL,
 CONSTRAINT [PK_NewsCategory] PRIMARY KEY CLUSTERED
(
    [Id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
 
GO

2、\Libraries\Nop.Core\Domain\News下面增加实体类,代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
using System;
using System.Collections.Generic;
using Nop.Core.Domain.Localization;
 
namespace Nop.Core.Domain.News
{
    /// <summary>
    /// Represents a news category
    /// </summary>
    public partial class NewsCategory : BaseEntity
    {
        /// <summary>
        /// Gets or sets the name
        /// </summary>
        public virtual string Name { get; set; }
 
        /// <summary>
        /// Gets or sets the description
        /// </summary>
        public virtual string Description { get; set; }
 
        /// <summary>
        /// Gets or sets the parent category identifier
        /// </summary>
        public virtual int ParentCategoryId { get; set; }
 
        /// <summary>
        /// Gets or sets a value indicating whether the entity is published
        /// </summary>
        public virtual bool Published { get; set; }
 
        /// <summary>
        /// Gets or sets a value indicating whether the entity has been deleted
        /// </summary>
        public virtual bool Deleted { get; set; }
 
        /// <summary>
        /// Gets or sets the display order
        /// </summary>
        public virtual int DisplayOrder { get; set; }
 
        /// <summary>
        /// Gets or sets the date and time of instance creation
        /// </summary>
        public virtual DateTime CreatedOn { get; set; }
 
        /// <summary>
        /// Gets or sets the date and time of instance update
        /// </summary>
        public virtual DateTime UpdatedOn { get; set; }
    }
}

3、\Libraries\Nop.Data\Mapping\News下面增加新闻类别映射类,因为nopcommerce使用Entity Framework (EF) Code-First方法, 允许你在nopcommerce代码中定义实体 (所有的核心实体类都在Nop.Core中定义),所以必须在此添加映射类,代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
using System.Data.Entity.ModelConfiguration;
using Nop.Core.Domain.News;
 
namespace Nop.Data.Mapping.News
{
    public partial class NewsCategoryMap : EntityTypeConfiguration<NewsCategory>
    {
        public NewsCategoryMap()
        {
            this.ToTable("NewsCategory");
            this.HasKey(bp => bp.Id);
            this.Property(bp => bp.Name).IsRequired().IsMaxLength();
            this.Property(bp => bp.Description).IsRequired().IsMaxLength();
        }
    }
}

4、\Libraries\Nop.Services\News下面的INewsService.cs和NewsService.cs增加新闻类别相关操作。 INewsService.cs整理后代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
using System;
using System.Collections.Generic;
using Nop.Core;
using Nop.Core.Domain.News;
 
namespace Nop.Services.News
{
    /// <summary>
    /// News service interface
    /// </summary>
    public partial interface INewsService
    {
        #region news
 
        /// <summary>
        /// Deletes a news
        /// </summary>
        /// <param name="newsItem">News item</param>
        void DeleteNews(NewsItem newsItem);
 
        /// <summary>
        /// Gets a news
        /// </summary>
        /// <param name="newsId">The news identifier</param>
        /// <returns>News</returns>
        NewsItem GetNewsById(int newsId);
 
        /// <summary>
        /// Gets all news
        /// </summary>
        /// <param name="languageId">Language identifier; 0 if you want to get all records</param>
        /// <param name="dateFrom">Filter by created date; null if you want to get all records</param>
        /// <param name="dateTo">Filter by created date; null if you want to get all records</param>
        /// <param name="pageIndex">Page index</param>
        /// <param name="pageSize">Page size</param>
        /// <param name="showHidden">A value indicating whether to show hidden records</param>
        /// <returns>News items</returns>
        IPagedList<NewsItem> GetAllNews(int languageId,
            DateTime? dateFrom, DateTime? dateTo, int pageIndex, int pageSize, bool showHidden = false);
 
        /// <summary>
        /// Inserts a news item
        /// </summary>
        /// <param name="news">News item</param>
        void InsertNews(NewsItem news);
 
        /// <summary>
        /// Updates the news item
        /// </summary>
        /// <param name="news">News item</param>
        void UpdateNews(NewsItem news);
        #endregion
 
        #region news category
 
        /// <summary>
        /// Deletes a news category
        /// </summary>
        /// <param name="category">News Category item</param>
        void DeleteNewsCategory(NewsCategory category);
 
        /// <summary>
        /// Gets a news category
        /// </summary>
        /// <param name="categoryId">The news category identifier</param>
        /// <returns>NewsCategory</returns>
        NewsCategory GetNewsCategoryById(int categoryId);
 
        /// <summary>
        /// Gets all news category
        /// </summary>
        /// <param name="pageIndex">Page index</param>
        /// <param name="pageSize">Page size</param>
        /// <param name="showHidden">A value indicating whether to show hidden records</param>
        /// <returns>News Category items</returns>
        IPagedList<NewsCategory> GetAllNewsCategory(int pageIndex, int pageSize, bool showHidden = false);
 
        /// <summary>
        /// Gets all news category
        /// </summary>
        /// <param name="showHidden">A value indicating whether to show hidden records</param>
        /// <returns>News Category items</returns>
        IList<NewsCategory> GetAllNewsCategory(bool showHidden = false);
 
        /// <summary>
        /// Inserts a news category item
        /// </summary>
        /// <param name="category">News Category item</param>
        void InsertNewsCategory(NewsCategory category);
 
        /// <summary>
        /// Updates the news category item
        /// </summary>
        /// <param name="category">News Category item</param>
        void UpdateNewsCategory(NewsCategory category);
 
        #endregion
    }
}

NewsService.cs整理后代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
using System;
using System.Collections.Generic;
using System.Linq;
using Nop.Core;
using Nop.Core.Caching;
using Nop.Core.Data;
using Nop.Core.Domain.News;
using Nop.Core.Events;
 
namespace Nop.Services.News
{
    /// <summary>
    /// News service
    /// </summary>
    public partial class NewsService : INewsService
    {
        #region Constants
        private const string NEWS_BY_ID_KEY = "Nop.news.id-{0}";
        private const string NEWS_PATTERN_KEY = "Nop.news.";
        private const string NEWSCATEGORY_BY_ID_KEY = "Nop.newscategory.id-{0}";
        private const string NEWSCATEGORY_PATTERN_KEY = "Nop.newscategory.";
        #endregion
 
        #region Fields
 
        private readonly IRepository<NewsItem> _newsItemRepository;
        private readonly IRepository<NewsCategory> _newsCategoryRepository;
        private readonly ICacheManager _cacheManager;
        private readonly IEventPublisher _eventPublisher;
 
        #endregion
 
        #region Ctor
 
        public NewsService(IRepository<NewsItem> newsItemRepository, IRepository<NewsCategory> newsCategoryRepository, ICacheManager cacheManager, IEventPublisher eventPublisher)
        {
            _newsItemRepository = newsItemRepository;
            _newsCategoryRepository = newsCategoryRepository;
            _cacheManager = cacheManager;
            _eventPublisher = eventPublisher;
        }
 
        #endregion
 
        #region Methods
 
        #region news
         
        /// <summary>
        /// Deletes a news
        /// </summary>
        /// <param name="newsItem">News item</param>
        public virtual void DeleteNews(NewsItem newsItem)
        {
            if (newsItem == null)
                throw new ArgumentNullException("newsItem");
 
            _newsItemRepository.Delete(newsItem);
 
            _cacheManager.RemoveByPattern(NEWS_PATTERN_KEY);
 
            //event notification
            _eventPublisher.EntityDeleted(newsItem);
        }
 
        /// <summary>
        /// Gets a news
        /// </summary>
        /// <param name="newsId">The news identifier</param>
        /// <returns>News</returns>
        public virtual NewsItem GetNewsById(int newsId)
        {
            if (newsId == 0)
                return null;
 
            string key = string.Format(NEWS_BY_ID_KEY, newsId);
            return _cacheManager.Get(key, () =>
            {
                var n = _newsItemRepository.GetById(newsId);
                return n;
            });
        }
 
        /// <summary>
        /// Gets all news
        /// </summary>
        /// <param name="languageId">Language identifier; 0 if you want to get all records</param>
        /// <param name="dateFrom">Filter by created date; null if you want to get all records</param>
        /// <param name="dateTo">Filter by created date; null if you want to get all records</param>
        /// <param name="pageIndex">Page index</param>
        /// <param name="pageSize">Page size</param>
        /// <param name="showHidden">A value indicating whether to show hidden records</param>
        /// <returns>News items</returns>
        public virtual IPagedList<NewsItem> GetAllNews(int languageId,
            DateTime? dateFrom, DateTime? dateTo, int pageIndex, int pageSize, bool showHidden = false)
        {
            var query = _newsItemRepository.Table;
            if (dateFrom.HasValue)
                query = query.Where(n => dateFrom.Value <= n.CreatedOnUtc);
            if (dateTo.HasValue)
                query = query.Where(n => dateTo.Value >= n.CreatedOnUtc);
            if (languageId > 0)
                query = query.Where(n => languageId == n.LanguageId);
            if (!showHidden)
                query = query.Where(n => n.Published);
            query = query.OrderByDescending(b => b.CreatedOnUtc);
 
            var news = new PagedList<NewsItem>(query, pageIndex, pageSize);
            return news;
        }
        /// <summary>
        /// Inserts a news item
        /// </summary>
        /// <param name="news">News item</param>
        public virtual void InsertNews(NewsItem news)
        {
            if (news == null)
                throw new ArgumentNullException("news");
 
            _newsItemRepository.Insert(news);
 
            _cacheManager.RemoveByPattern(NEWS_PATTERN_KEY);
 
            //event notification
            _eventPublisher.EntityInserted(news);
        }
 
        /// <summary>
        /// Updates the news item
        /// </summary>
        /// <param name="news">News item</param>
        public virtual void UpdateNews(NewsItem news)
        {
            if (news == null)
                throw new ArgumentNullException("news");
 
            _newsItemRepository.Update(news);
 
            _cacheManager.RemoveByPattern(NEWS_PATTERN_KEY);
 
            //event notification
            _eventPublisher.EntityUpdated(news);
        }
 
        #endregion
 
        #region news category
 
        /// <summary>
        /// Deletes a news category
        /// </summary>
        /// <param name="category">News Category item</param>
        public virtual void DeleteNewsCategory(NewsCategory category)
        {
            if (category == null)
                throw new ArgumentNullException("category");
 
            _newsCategoryRepository.Delete(category);
 
            _cacheManager.RemoveByPattern(NEWSCATEGORY_PATTERN_KEY);
 
            //event notification
            _eventPublisher.EntityDeleted(category);
        }
 
        /// <summary>
        /// Gets a news category
        /// </summary>
        /// <param name="categoryId">The news category identifier</param>
        /// <returns>NewsCategory</returns>
        public virtual NewsCategory GetNewsCategoryById(int categoryId)
        {
            if (categoryId == 0)
                return null;
 
            string key = string.Format(NEWSCATEGORY_BY_ID_KEY, categoryId);
            return _cacheManager.Get(key, () =>
            {
                var n = _newsCategoryRepository.GetById(categoryId);
                return n;
            });
        }
 
        /// <summary>
        /// Gets all news category
        /// </summary>
        /// <param name="pageIndex">Page index</param>
        /// <param name="pageSize">Page size</param>
        /// <param name="showHidden">A value indicating whether to show hidden records</param>
        /// <returns>News Category items</returns>
        public virtual IPagedList<NewsCategory> GetAllNewsCategory(int pageIndex, int pageSize, bool showHidden = false)
        {
            var categories = GetAllNewsCategory(showHidden);
            return new PagedList<NewsCategory>(categories, pageIndex, pageSize);
        }
 
        /// <summary>
        /// Gets all news category
        /// </summary>
        /// <param name="showHidden">A value indicating whether to show hidden records</param>
        /// <returns>News Category items</returns>
        public virtual IList<NewsCategory> GetAllNewsCategory(bool showHidden = false)
        {
            var query = _newsCategoryRepository.Table;
            if (!showHidden)
                query = query.Where(n => n.Published);
            query = query.OrderBy(b => b.DisplayOrder);
 
            var unsortedCategories = query.ToList();
 
            //sort categories
            var sortedCategories = unsortedCategories.SortCategoriesForTree(0);
            return sortedCategories;
        }
 
        /// <summary>
        /// Inserts a news category item
        /// </summary>
        /// <param name="category">News Category item</param>
        public virtual void InsertNewsCategory(NewsCategory category)
        {
            if (category == null)
                throw new ArgumentNullException("category");
 
            _newsCategoryRepository.Insert(category);
 
            _cacheManager.RemoveByPattern(NEWSCATEGORY_PATTERN_KEY);
 
            //event notification
            _eventPublisher.EntityInserted(category);
        }
 
        /// <summary>
        /// Updates the news category item
        /// </summary>
        /// <param name="category">News Category item</param>
        public virtual void UpdateNewsCategory(NewsCategory category)
        {
            if (category == null)
                throw new ArgumentNullException("category");
 
            _newsCategoryRepository.Update(category);
 
            _cacheManager.RemoveByPattern(NEWSCATEGORY_PATTERN_KEY);
 
            //event notification
            _eventPublisher.EntityUpdated(category);
        }
 
        #endregion
 
        #endregion
    }
}

另外需要增加NewsExtensions.cs,主要用于新闻类别的排序(对无限极分类的排序等等),代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
using System;
using System.Collections.Generic;
using System.Linq;
using Nop.Core.Domain.News;
 
namespace Nop.Services.News
{
    /// <summary>
    /// Extensions
    /// </summary>
    public static class NewsExtensions
    {
        /// <summary>
        /// Sort news categories for tree representation
        /// </summary>
        /// <param name="source">Source</param>
        /// <param name="parentId">Parent category identifier</param>
        /// <returns>Sorted categories</returns>
        public static IList<NewsCategory> SortCategoriesForTree(this IList<NewsCategory> source, int parentId)
        {
            var result = new List<NewsCategory>();
 
            var temp = source.ToList().FindAll(c => c.ParentCategoryId == parentId);
            foreach (var cat in temp)
            {
                result.Add(cat);
                result.AddRange(SortCategoriesForTree(source, cat.Id));
            }
            return result;
        }
 
        public static string GetCategoryNameWithPrefix(this NewsCategory category, INewsService newsService)
        {
            string result = string.Empty;
 
            while (category != null)
            {
                if (String.IsNullOrEmpty(result))
                    result = category.Name;
                else
                    result = "--" + result;
                category = newsService.GetNewsCategoryById(category.ParentCategoryId);
            }
            return result;
        }
 
        public static string GetCategoryBreadCrumb(this NewsCategory category, INewsService newsService)
        {
            string result = string.Empty;
 
            while (category != null && !category.Deleted)
            {
                if (String.IsNullOrEmpty(result))
                    result = category.Name;
                else
                    result = category.Name + " >> " + result;
 
                category = newsService.GetNewsCategoryById(category.ParentCategoryId);
 
            }
            return result;
        }
 
    }
}

5、到此底层的数据操作已经基本完成,开始修改后台管理部分。 Nop.Admin\Models\News\增加新闻类别页面所需要的ViewModel,代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
using System;
using System.Collections.Generic;
using System.Web.Mvc;
using FluentValidation.Attributes;
using Nop.Admin.Validators.News;
using Nop.Web.Framework;
using Nop.Web.Framework.Mvc;
 
namespace Nop.Admin.Models.News
{
    [Validator(typeof(NewsCategoryValidator))]
    public class NewsCategoryModel : BaseNopEntityModel
    {
        public NewsCategoryModel()
        {
            AvailableCategories = new List<SelectListItem>();
        }
 
        [NopResourceDisplayName("Admin.ContentManagement.News.NewsCategoryItems.Fields.Name")]
        public string Name { get; set; }
 
        [NopResourceDisplayName("Admin.ContentManagement.News.NewsCategoryItems.Fields.Description")]
        [AllowHtml]
        public string Description { get; set; }
 
        [NopResourceDisplayName("Admin.ContentManagement.News.NewsCategoryItems.Fields.ParentName")]
        public int ParentCategoryId { get; set; }
 
        [NopResourceDisplayName("Admin.ContentManagement.News.NewsCategoryItems.Fields.ParentName")]
        public string ParentCategoryName { get; set; }
 
        [NopResourceDisplayName("Admin.ContentManagement.News.NewsCategoryItems.Fields.Published")]
        public bool Published { get; set; }
 
        [NopResourceDisplayName("Admin.ContentManagement.News.NewsCategoryItems.Fields.DisplayOrder")]
        public int DisplayOrder { get; set; }
 
        [NopResourceDisplayName("Admin.ContentManagement.News.NewsCategoryItems.Fields.CreatedOn")]
        public DateTime CreatedOn { get; set; }
 
        public IList<SelectListItem> AvailableCategories { get; set; }
    }
}

Nop.Admin\Validators\News\增加类别的验证类NewsCategoryValidator.cs,主要用于后台添加时候的非空字数限制等等,代码如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
using FluentValidation;
using Nop.Admin.Models.News;
using Nop.Services.Localization;
 
namespace Nop.Admin.Validators.News
{
    public class NewsCategoryValidator : AbstractValidator<NewsCategoryModel>
    {
        public NewsCategoryValidator(ILocalizationService localizationService)
        {
            RuleFor(x => x.Name)
                .NotNull()
                .WithMessage(localizationService.GetResource("Admin.ContentManagement.News.NewsCategoryItems.Fields.Name.Required"));
 
            RuleFor(x => x.Description)
                .NotNull()
                .WithMessage(localizationService.GetResource("Admin.ContentManagement.News.NewsCategoryItems.Fields.Description.Required"));
        }
    }
}

修改Nop.Admin/MappingExtensions.cs文件,增加新闻类别相关内容,这几个方法主要是NewsCategoryNewsCategoryModel之间的相互转换,代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//news category items
        public static NewsCategoryModel ToModel(this NewsCategory entity)
        {
            return Mapper.Map<NewsCategory, NewsCategoryModel>(entity);
        }
 
        public static NewsCategory ToEntity(this NewsCategoryModel model)
        {
            return Mapper.Map<NewsCategoryModel, NewsCategory>(model);
        }
 
        public static NewsCategory ToEntity(this NewsCategoryModel model, NewsCategory destination)
        {
            return Mapper.Map(model, destination);
        }

修改Nop.Admin/Infrastructure/AutoMapperStartupTask.cs文件,增加相关映射规则,如果不加的话会出错的哦, AutoMapper是基于对象到对象约定的映射工具,常用于(但并不仅限制于)把复杂的对象模型转为DTO,一般用于ViewModel模式和跨服务范畴。 AutoMapper给用户提供了便捷的配置API,就像使用约定来完成自动映射那样。 代码如下:

1
2
3
4
5
6
Mapper.CreateMap<NewsCategory, NewsCategoryModel>()
                .ForMember(dest => dest.AvailableCategories, mo => mo.Ignore())
                .ForMember(dest => dest.ParentCategoryName, mo => mo.Ignore())
                .ForMember(dest => dest.CreatedOn, mo => mo.Ignore());
            Mapper.CreateMap<NewsCategoryModel, NewsCategory>()
                .ForMember(dest => dest.CreatedOn, mo => mo.Ignore());

最后修改Nop.Admin\Controllers\NewsController.cs,增加新闻类别的增删改查操作,如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
#region News category items
        public ActionResult CategoryList()
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageNews))
                return AccessDeniedView();
 
            var news = _newsService.GetAllNewsCategory(0, _adminAreaSettings.GridPageSize, true);
            var gridModel = new GridModel<NewsCategoryModel>
            {
                Data = news.Select(x =>
                {
                    var m = x.ToModel();
                    m.CreatedOn = _dateTimeHelper.ConvertToUserTime(x.CreatedOn, DateTimeKind.Utc);
                    m.Name = x.GetCategoryBreadCrumb(_newsService);
                    m.Published = x.Published;
                    m.DisplayOrder = x.DisplayOrder;
                    return m;
                }),
                Total = news.TotalCount
            };
            return View(gridModel);
        }
 
        [HttpPost, GridAction(EnableCustomBinding = true)]
        public ActionResult CategoryList(GridCommand command)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageNews))
                return AccessDeniedView();
 
            var news = _newsService.GetAllNewsCategory(0, _adminAreaSettings.GridPageSize, true);
            var gridModel = new GridModel<NewsCategoryModel>
            {
                Data = news.Select(x =>
                {
                    var m = x.ToModel();
                    m.CreatedOn = _dateTimeHelper.ConvertToUserTime(x.CreatedOn, DateTimeKind.Utc);
                    m.Name = x.GetCategoryBreadCrumb(_newsService);
                    m.Published = x.Published;
                    m.DisplayOrder = x.DisplayOrder;
                    return m;
                }),
                Total = news.TotalCount
            };
            return new JsonResult
            {
                Data = gridModel
            };
        }
 
        public ActionResult CategoryCreate()
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageNews))
                return AccessDeniedView();
 
            var model = new NewsCategoryModel();
            //default values
            model.Published = true;
 
            //categories
            model.AvailableCategories.Add(new SelectListItem() { Text = _localizationService.GetResource("Admin.Common.All"), Value = "0" });
            foreach (var c in _newsService.GetAllNewsCategory(true))
                model.AvailableCategories.Add(new SelectListItem() { Text = c.GetCategoryNameWithPrefix(_newsService), Value = c.Id.ToString() });
 
            return View(model);
        }
        [HttpPost, FormValueExists("save", "save-continue", "continueEditing")]
        public ActionResult CategoryCreate(NewsCategoryModel model, bool continueEditing)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageNews))
                return AccessDeniedView();
 
            if (ModelState.IsValid)
            {
                var newsItem = model.ToEntity();
                newsItem.CreatedOn = DateTime.UtcNow;
                newsItem.UpdatedOn = DateTime.UtcNow;
                _newsService.InsertNewsCategory(newsItem);
 
                SuccessNotification(_localizationService.GetResource("Admin.ContentManagement.News.NewsCategoryItems.Added"));
                return continueEditing ? RedirectToAction("CategoryEdit", new { id = newsItem.Id }) : RedirectToAction("CategoryList");
            }
 
            return View(model);
        }
 
        public ActionResult CategoryEdit(int id)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageNews))
                return AccessDeniedView();
 
            var newsItem = _newsService.GetNewsCategoryById(id);
            if (newsItem == null)
                //No news item found with the specified id
                return RedirectToAction("CategoryList");
 
            var model = newsItem.ToModel();
            //categories
            model.AvailableCategories.Add(new SelectListItem() { Text = _localizationService.GetResource("Admin.Common.All"), Value = "0" });
            foreach (var c in _newsService.GetAllNewsCategory(true))
                model.AvailableCategories.Add(new SelectListItem() { Text = c.GetCategoryNameWithPrefix(_newsService), Value = c.Id.ToString() });
 
            return View(model);
        }
 
        [HttpPost, FormValueExists("save", "save-continue", "continueEditing")]
        public ActionResult CategoryEdit(NewsCategoryModel model, bool continueEditing)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageNews))
                return AccessDeniedView();
 
            var newsItem = _newsService.GetNewsCategoryById(model.Id);
            if (newsItem == null)
                //No news item found with the specified id
                return RedirectToAction("CategoryList");
 
            if (ModelState.IsValid)
            {
                newsItem = model.ToEntity(newsItem);
                newsItem.UpdatedOn = DateTime.UtcNow;
                _newsService.UpdateNewsCategory(newsItem);
 
                SuccessNotification(_localizationService.GetResource("Admin.ContentManagement.News.NewsCategoryItems.Updated"));
                return continueEditing ? RedirectToAction("CategoryEdit", new { id = newsItem.Id }) : RedirectToAction("List");
            }
 
            return View(model);
        }
 
        [HttpPost, ActionName("DeleteCategory")]
        public ActionResult DeleteCategoryConfirmed(int id)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageNews))
                return AccessDeniedView();
 
            var newsItem = _newsService.GetNewsCategoryById(id);
            if (newsItem == null)
                //No news item found with the specified id
                return RedirectToAction("CategoryList");
 
            _newsService.DeleteNewsCategory(newsItem);
 
            SuccessNotification(_localizationService.GetResource("Admin.ContentManagement.News.NewsCategoryItems.Deleted"));
            return RedirectToAction("CategoryList");
        }
 
        #endregion

6、接下来就是页面View了,代码太多,这里不再具体列出,不熟悉MVC机制的可以先补充一下MVC相关知识。 稍后整理提供下载。

[转]教你一招 - 如何给nopcommerce增加新闻类别模块的更多相关文章

  1. [转]教你一招 - 如何给nopcommerce增加一个类似admin的area

    本文转自:http://www.cnblogs.com/wucf2004/p/nopcommerce-area.html asp.net mvc里面的area是什么,点击这里查看 如果在nopcomm ...

  2. 教你一招 - 如何给nopcommerce增加一个类似admin的area

    asp.net mvc里面的area是什么,点击这里查看 如果在nopcommerce里面加入类似admin的area,步骤如下: 1.新建一个mvc空项目MvcApplication1,位置放在\N ...

  3. 教你一招 - 如何给nopcommerce做一套自己的主题

    nopcommerce拥有一套不错的模板机制,可以让你快速的做一套属于自己的主题.\Presentation\Nop.Web下面有个Themes文件夹,这里面就是放主题的地方,每个主题对应一个文件夹, ...

  4. 教你一招 - 如何安装nopcommerce2.5

    教你一招 - 如何安装nopcommerce2.5 29. 五月 2012 16:22         /          wcf         /          教你一招 . 解决方案    ...

  5. IE-“无法浏览网页” 教你十招解决疑难杂症

    “无法浏览网页” 教你十招解决疑难杂症 相信大家也有遇到过像IE不能上网浏览的问题.下面就来给大家介绍一下常见原因和解决方法: 一.网络设置的问题 这种原因比较多出现在需要手动指定IP.网关.DNS服 ...

  6. 文章如何做伪原创 SEO大神教你几招做"原创"网站文章的心得

    想要创作出好的文章并被百度所喜欢,就非常需要SEO的优化能力,以及要对文章进行塬创或伪塬创,那么,如何做伪塬创文章?以及如何做好塬创网站文章呢?对此,本文小编就为大家带来了几招做"塬创&qu ...

  7. PDF怎么替换页面,教你一招秒实现

    PDF格式是在办公中比较常用的文件格式之一,虽然很好用,也很容易携带,但也容易出现一个问题,当你想要对PDF文件操作或者修改的时候,才发现PDF文件不是那么容易就能进行编辑和修改的,特别是需要对PDF ...

  8. 线上Bug无法复现怎么办?老司机教你一招,SpringBoot远程调试不用愁!

    前言 在部署线上项目时,相信大家都会遇到一个问题,线上的 Bug 但是在本地不会复现,多么无奈. 此时最常用的就是取到前端传递的数据用接口测试工具测试,比如 POSTMAN,复杂不,难受不? 今天陈某 ...

  9. NopCommerce 增加 Customer Field

    预期效果: Customer表新增一个Column 该新增字段可以在Admin段 新增 修改 列表查询及显示 示例步骤: 0.数据库表修改 alter table [Customer] add Mem ...

随机推荐

  1. JQuery读取XML文件

    <?xml version="1.0" encoding="utf-8" ?> <taxrates> <taxrate id=&q ...

  2. clicaptcha中文点击验证码开发经验总结

    现在的验证码真是越来越高级了,12306 的找图验证码,极验的拖动式验证码,还有国外的一些黑科技,能智能判断你是不是机器人的验证码. 验证码的更新迭代让我突然对传统验证码一下子不满足了,出于挑战自我和 ...

  3. Popline:帅气的浮动 HTML5 文本编辑器工具栏

    Popline 是一个基于 HTML5 实现的富文本编辑器工具栏,设计灵感来自 PopClip ,相比传统的文本编辑器工具,Popline 能够浮动在编辑的文本周围,操作起来十分方便. 您可能感兴趣的 ...

  4. css对齐

    2016-10-25 <css入门经典>第15章 1.text-align属性: 块属性内部的文本对齐方式.该属性只对块盒子有意义,内联盒子的内容没有对齐方式.(注意:只是盒子内部的内容对 ...

  5. JavaScript基础系列(变量与类型)

    以下内容将JavaScript简称为JS 打开本文时不管你是零基础的初学者还是其他语言的老兵,我都想说程序语言的基础支撑起了整个网络世界,不把这些基础学透之后稍复杂的内容会让你寸步难行. 现在先给编程 ...

  6. ArcGIS JS 学习笔记2 实现仿百度的拖拽画圆

    一.前言 吐槽一下,百度在国内除了百度地图是良心产品外,其他的真的不敢恭维.在上一篇笔记里,我已经实现了自定义的地图测量模块.在百度地图里面(其他地图)都有一个周边搜索的功能,拖拽画一个圆,然后以圆半 ...

  7. sharepoint2010问卷调查(4)-实现问卷的重复答复次数(采用自定义字段类型和JS)

    sharepoint的问卷调查可以设置重复和一次答复.但是设置一次后,调查过的用户再进行答复.会提示如下图: 分析下:该提示用户体验很不好.给用户感觉是系统出问题了.因此网上有人提出用eventhan ...

  8. 解决在使用client object model的时候报“object does not belong to a list”错误

    在查看别人代码的时候,发现了个有意思的问题,使用client object model将一个文件check in 我使用的是如下语句获取file Microsoft.SharePoint.Client ...

  9. 怎么让一个项目里swift与OC可以兼容混合开发?

    在苹果推出了swift语言之后,很多人担心OC很快会被取代,但是苹果方面表示2年内不会摒弃OC.但现在也快了啊.有的开发团队已经开始基于swift开发,但是有很多旧的框架还没来得及用swift写出来, ...

  10. Binder中的asInterface解析

    在使用AIDL通信的时候,在Stub类中都会生成一个asInterface函数,以<Android开发艺术探索>中的例子来分析,其生成的asInterface函数源码为: /** * Ca ...