我需要使用代碼創建內容項目。我知道有內置的方式,但我希望我自己的模塊功能。我嘗試了代碼,但它給了我錯誤。所有相關的代碼如下。內容部分名稱爲「課程」,內容項目名稱爲「課程」通過Orchard CMS中的代碼創建內容項目
「對象引用未設置爲對象的實例」。
[HiddenInput(DisplayValue = false)]
public int Id {
get { return ContentItem.Id; }
}
**Controller**
public ActionResult Create()
{
var course = _orchardService.ContentManager.New("Courses");
dynamic model = _orchardService.ContentManager.BuildEditor(course);
return View((object)model);
}
[HttpPost, ActionName("Create")]
public ActionResult CreatePOST(string idl)
{
var contentItem = _contentManager.New("Courses");
_contentManager.Create(contentItem, VersionOptions.Draft);
dynamic model = _contentManager.UpdateEditor(contentItem, this);
_contentManager.Publish(contentItem);
_orchardService.Notifier.Information(new LocalizedString("Your content has been created."));
var adminRouteValues = _contentManager.GetItemMetadata(contentItem).AdminRouteValues;
return RedirectToRoute(adminRouteValues);
}
public ActionResult Index(PagerParameters pagerParameters, CourseSearchVM search)
{
//this is displaying only published content
var courseQuery = _contentManager.Query<CoursePart>().List().ToList();
// Project the query into a list of customer shapes
var coursesProjection = from course in courseQuery
select Shape.course
(
Id: course.Id,
Name: course.Name,
Description: course.Description
);
// The pager is used to apply paging on the query and to create a PagerShape
var pager = new Pager(_siteService.GetSiteSettings(), pagerParameters.Page, pagerParameters.PageSize);
// Apply paging
var coures = coursesProjection.Skip(pager.GetStartIndex()).Take(pager.PageSize);
// Construct a Pager shape
var pagerShape = Shape.Pager(pager).TotalItemCount(courseQuery.Count());
// Create the viewmodel
var model = new CourseIndexVM(coures, search, pagerShape);
return View(model);
}
**CoursePart Model**
public class CoursePart : ContentPart<CoursePartRecord>
{
public string Name
{
get { return Record.Name; }
set { Record.Name = value; }
}
public string Description
{
get { return Record.Description; }
set { Record.Description = value; }
}
}
public class CoursePartRecord : ContentPartRecord
{
public virtual string Name { get; set; }
public virtual string Description { get; set; }
}
**Create.cshtml**
@{ Layout.Title = "Edit Course"; }
@using(Html.BeginFormAntiForgeryPost())
{
@Display(Model)
}
**Course.cshtml**
@model Course.Models.CoursePart
<fieldset>
<div class="editor-label">@Html.LabelFor(x => x.Name)</div>
<div class="editor-field">
@Html.EditorFor(x => x.Name)
@Html.ValidationMessageFor(x => x.Name)
</div>
<div class="editor-label">@Html.LabelFor(x => x.Description)</div>
<div class="editor-field">
@Html.EditorFor(x => x.Description)
@Html.ValidationMessageFor(x => x.Description)
</div>
</fieldset>
您是否嘗試過調試以查看引發異常的行?我認爲。如果內容項沒有你要轉換的內容部分,那麼<>()返回null,當你嘗試設置名稱和描述時會導致NullReferenceException,所以檢查是否你的內容類型有這個部分。 – mdm