Sitecore MVC控制器

Sitecore MVC控制器,sitecore,sitecore-mvc,Sitecore,Sitecore Mvc,我的视图中有“firstname”字段。 我的问题是如何使用我的控制器手动添加值或操纵字段。 注意:我的视图已连接到Index.cshtml文件,我的控制器名称为FormsController Firstname: @Html.Sitecore().Field("firstname") 最有可能的情况是,您可以根据需要修改RenderingContext.Current.Rendering.Item,但还有其他变体可用。看看这几篇描述可用选项的好文章。或者在视图中为变量分配@Html.Site

我的视图中有“firstname”字段。 我的问题是如何使用我的控制器手动添加值或操纵字段。 注意:我的视图已连接到Index.cshtml文件,我的控制器名称为FormsController

Firstname: @Html.Sitecore().Field("firstname")

最有可能的情况是,您可以根据需要修改
RenderingContext.Current.Rendering.Item
,但还有其他变体可用。看看这几篇描述可用选项的好文章。

或者在视图中为变量分配@Html.Sitecore().Field(“firstname”),并在视图中执行逻辑(不是最好的MVC方法)


或者在控制器中创建一个分部类来扩展要传递给视图的模型,该模型具有已操纵的名字值。

如果要操纵Sitecore中的项目,这是一种方法,尽管您通常不希望从代码中编辑Sitecore项目:

        var sitecoreItem = Sitecore.Context.Item;
        sitecoreItem = Sitecore.Data.Database.GetDatabase("master").GetItem(sitecoreItem.ID);
        using (new EditContext(sitecoreItem, SecurityCheck.Disable))
        {
            sitecoreItem["Navigation title"] = "I have just Edited";
        }

请注意,我首先从主数据库获取项目,然后从主数据库获取项目,因为从web数据库编辑项目没有什么意义。

正如我从您提供的代码中看到的,我指的是这种代码的和平:

@Html.Sitecore().Field("firstname")
您希望使用上下文项的“firstname”字段进行操作。 如果是这样的话,您需要在控制器的适当操作中执行以下操作:

using (new Sitecore.SecurityModel.SecurityDisabler())
{
    Sitecore.Context.Item.Editing.BeginEdit();
    try
    {
        Sitecore.Context.Item["firstname"] = "set value you want";      
        Sitecore.Context.Item.Editing.EndEdit();
    }
    catch (Exception)
    {       
        Sitecore.Context.Item.Editing.CancelEdit();
    }
}

注意:使用SecurityDisabler()意味着您的上下文用户可能没有上下文项的权限。所以这只是一个例子。使用

授予对必要项的适当访问权限的最佳做法是否将模型传递给视图?在将模型传递到视图之前,您无法获得字段值!
using (new Sitecore.SecurityModel.SecurityDisabler())
{
    Sitecore.Context.Item.Editing.BeginEdit();
    try
    {
        Sitecore.Context.Item["firstname"] = "set value you want";      
        Sitecore.Context.Item.Editing.EndEdit();
    }
    catch (Exception)
    {       
        Sitecore.Context.Item.Editing.CancelEdit();
    }
}