Orchard之Module開發

一:生成新項目css

首先,要啓動 Code Generation,參考《Orchard之生成新模板》。html

其次,進入命令行,輸入:sql

codegen module Tminji.Requirement數據庫

這會在解決方案中生成一個新項目,以下:ide

image

 

二:路由匹配ui

在新項目中建立 Routes.CS 文件,編碼以下:編碼

public class Routes : IRouteProvider {
    #region IRouteProvider 成員 hibernate

    public IEnumerable<RouteDescriptor> GetRoutes() {
        return new[] {
            new RouteDescriptor {
                Priority = 5,
                Route = new Route
                    (
                    "Requirement/{controller}/{action}/",
                    new RouteValueDictionary
                    {
                        {"area", "Tminji.Requirement"},
                        {"controller", "Home"},
                        {"action", "Index"}
                    },
                    new RouteValueDictionary(),
                    new RouteValueDictionary {{"area", "Tminji.Requirement"}},
                    new MvcRouteHandler()
                    )
            }
        };
    } 命令行

    public void GetRoutes(ICollection<RouteDescriptor> routes) {
        foreach (var routeDescriptor in GetRoutes()) {
            routes.Add(routeDescriptor);
        }
    } 3d

    #endregion
}

 

三:新建控制器吧

接下來,就跟咱們熟悉的 MVC 開發同樣了,新建控制器,相似以下,能夠建立視圖,也能夠沒有視圖,總之,輸入 URL ,就會執行控制器代碼了:

public class HomeController : Controller {
    public IOrchardServices Services { get; set; }

    public HomeController(IOrchardServices services) {
        Services = services;
        T = NullLocalizer.Instance;
    }

    public Localizer T { get; set; }

    public ActionResult Index()
    {
        string model = "Hello World!"; 
        return View((object)model);    
    }
    public string About()
    {
        return "About me";
    }

}

 

四:在後臺啓用之

以下:

image

 

五:實效

image

或:

image

 

六:操做數據庫

若是上面顯式的文本咱們要存儲在數據庫,那麼,怎麼實現?

1:建立數據庫表

咱們能夠有兩種方式來建立數據庫表,一種是經過 Module 的 Update,咱們須要在項目的根目錄下建立一個文件 Migrations.CS,內容大體以下:

public class Migrations : DataMigrationImpl
{
    public int Create()
    {
        return 1;
    }

    public int UpdateFrom1()
    {
        SchemaBuilder.CreateTable("RequirementRecord", table => table
            .ContentPartVersionRecord()
            .Column<int>("Id", column => column.PrimaryKey().Identity())
            .Column<string>("Content", column => column.WithLength(200))
        );
        ContentDefinitionManager.AlterPartDefinition("Tminji.Requirement",
            builder => builder.Attachable());
        return 2;
    }
}

這樣,在咱們下次登陸後臺的時候,就會在 Module 旁邊,看到 Update,而後點擊後,就會執行上述代碼。

還有一種,固然是手動建立數據庫表,這沒有什麼影響。數據庫表是這樣的:

image

2:實現後臺管理這個 Content 的值

首先,咱們得在 根目錄下建立AdminMenu類型(備註:ORCHARD下不少命名都是固定死的,不能本身改變),以下:

public class AdminMenu : INavigationProvider {
    public Localizer T { get; set; }

    #region INavigationProvider 成員

    /* 指定這個菜單是一個管理菜單
     */
    public string MenuName {
        get { return "admin"; }
    }

    public void GetNavigation(NavigationBuilder builder) {
        builder
            .AddImageSet("Requirement") //設置菜單圖標(Orchard中默認約定調用Styles目錄下的menu.xxxxxx-admin.css樣式文件來顯示菜單前面的圖標)
            .Add(
                T("Requirement"), //菜單文本
                "5", //菜單位置(Orchard會根據這個值對菜單進行排序)
                menu => menu.Action(new RouteValueDictionary
                    {
                        {"area", "Tminji.Requirement"},
                        {"controller", "Admin"},
                        {"action", "Index"}
                    })
            );
    }
    #endregion
}

其次,咱們建立 AdminController(固定死),編碼以下:

public class AdminController : Controller
{
    // GET: Admin
    private readonly IRequirementService _textService;

    public AdminController(IRequirementService textService)
    {
        _textService = textService;
    }

    public ActionResult Index()
    {
        var viewModel = new RequirementPart();
        var textRecord = _textService.GetText();

        if (textRecord != null)
        {
            viewModel.Content = textRecord.Content;
        }

        return View(viewModel);
    }

    [HttpPost, ActionName("Index")]
    [FormValueRequired("submit.Save")]
    public ActionResult IndexPost()
    {
        var viewModel = new RequirementPart();

        if (!TryUpdateModel(viewModel))
        {
            return Index();
        }

        //更新數據
        _textService.UpdateText(viewModel.Content);

        return RedirectToAction("Index");
    }
}

前臺代碼以下:

image

Admin下的 index.cshtml:

@using Tminji.Requirement.Models
@model RequirementPart

<!--設置標題-->
@{ Layout.Title = T("Manage Hello World Text").ToString(); }

@Html.ValidationSummary()

@using (Html.BeginFormAntiForgeryPost())
{
    <fieldset>
        @Html.LabelFor(m => m.Content)
        @Html.TextBoxFor(m => m.Content, new { @class = "text" })
    </fieldset>
    <fieldset>
        <button class="primaryAction" type="submit" name="submit.Save" value="yes">@T("Save")</button>
    </fieldset>
}

3:數據訪問層

orchard 的數據訪問層是使用 nhibernate 實現的,咱們一樣能夠把其換成 ADO.NET 的,注意上面的控制器中,存在 IRequirementService,以及隱藏存在的這個接口的一個實現類(ORCHARD)自動會爲咱們找到它並注入到控制器中,在這裏,咱們能夠這樣實現:

public interface IRequirementService : IDependency
{
    RequirementPart GetText();

    RequirementPart UpdateText(string content);
}

[UsedImplicitly]
public class RequirementService : IRequirementService
{
    private readonly IRepository<Requirement> _textRepository;

    public RequirementPartService(IRepository<Requirement> textRepository)
    {
        _textRepository = textRepository;
    }

    #region ITextService 成員

    public Requirement GetText()
    {
        var conn = @"Data Source=xxx;Initial Catalog=OrchardOk1;Persist Security Info=True;User ID=sa;Password=xxx";
        var sql = @"SELECT * FROM RequirementRecord";
        var ds = SqlHelper.ExecuteDataset(conn, CommandType.Text, sql, null);
        if (ds.Tables[0].Rows.Count == 0)
            return null;
        return new Requirement()
        {
            Id = (int)ds.Tables[0].Rows[0][0],
            Content = (string)ds.Tables[0].Rows[0][1]
        };
    }

    public Requirement UpdateText(string content)
    {
        var conn = @"Data Source=xxx;Initial Catalog=OrchardOk1;Persist Security Info=True;User ID=sa;Password=xxx";
        string sql = "";
        var m = GetText();
        if (m == null)
        {
            sql = "INSERT INTO RequirementRecord (ID, [CONTENT]) VALUES (1, @CONTENT)";
        }
        else
        {
            sql = @"UPDATE RequirementRecord SET [CONTENT]=@CONTENT";
        }

        var pms = new SqlParameter[] {
            new SqlParameter("@CONTENT", content)
        };
        SqlHelper.ExecuteNonQuery(conn, CommandType.Text, sql, pms);
        return new Requirement()
        {
            Id = 1,
            Content = content,
        };
    }

    #endregion
}

至於 home/index 這裏,同理,就不在贅述了。

後臺管理的實效以下:

image

相關文章
相關標籤/搜索