1

你好,我想在数据库中保存 umbraco 表单的值,为此我制作了脚本文件,在这个脚本文件中我创建了保存数据的函数,并在同一个脚本文件中调用了这个函数,这个脚本文件用于宏,我有在我的页面模板中调用了这个宏,但它不起作用,这种方法是否合适,或者我必须做其他事情,我的基本目标是在不创建用户控件的情况下将数据保存在数据库中

代码是

@functions
{
    public void AddToCart()
    {
        string con = System.Configuration.ConfigurationManager.AppSettings["umbracoDbDSN"].ToString();
        SqlConnection OnCon = new SqlConnection(System.Configuration.ConfigurationManager.AppSettings["umbracoDbDSN"].ToString());
        ItemsDataContext db = new ItemsDataContext(con);
        var request = HttpContext.Current.Request;
        string itemcode= request.Form["ItemCode"].ToString();
        string itemname = request.Form["ItemName"].ToString();
        string itemcategory = Request.Form["ItemCategory"].ToString();
        string userid = "Pallavi";
        db.sp_AddItems(userid, itemcode, itemcategory, itemname, 0);


        HttpContext.Current.Session["UserId"] = "Pallavi";
    }
}


@if (!IsPost)
{
    AddToCart();
}

并在模板上调用这个宏

<umbraco:Macro Alias="Uc_Cart" runat="server"></umbraco:Macro>
4

1 回答 1

6

你的做法是错误的。您必须使用 Umbraco 在其 API 中提供的方法,并且不要尝试将数据直接写入数据库。

尝试使用此代码从 Razor 代码创建一个新文档:

@using umbraco.BusinessLogic;
@using umbraco.cms.businesslogic.web;
@{
    DocumentType dt = DocumentType.GetByAlias("Textpage"); 
    User author = umbraco.BusinessLogic.User.GetUser(0); 
    Document doc = Document.MakeNew("My new document", dt, author, parentID); 
}

上面的示例适用于 Umbraco 4.x。如果您使用的是 Umbraco v6.x,您还可以使用新的 API 方法:

@{
    // get an instance of the contentService
    var contentService = ApplicationContext.Services.ContentService;
    // create new content, the last param is the userId and is optional [default = 0]
    IContent newContent = contentService.CreateContent("My new document", parentID, "Textpage", 0);
    // set property values
    newContent.SetValue("propertyAlias", "Value");
    // save (or save and publish)
    contentService.Save(newContent);
}
于 2013-03-14T12:10:02.820 回答