Jay
Jay

Reputation: 1201

Sitecore MVC Field Update Programmatically

How can I change field value by using MVC?

I have a form in view like this and defined Controll Name and Action in ViewRendering Item.

@using (Html.BeginRouteForm(Sitecore.Mvc.Configuration.MvcSettings.SitecoreRouteName, System.Web.Mvc.FormMethod.Post))
{
    @Html.Sitecore().FormHandler("Components", "testController")

    @Html.DropDownListFor(model => model.TypeList, new List<SelectListItem> 
        { 
            new SelectListItem{Text="Enable", Value="True", Selected = (isSet ? true : false)},
            new SelectListItem{Text="Disable", Value="False", Selected = (!isSet ? true : false)}
        })

    <input type="submit" name="submit" value="submit"/>
}

What I want to do is when "submit" clicked, controller gets the form data and update field value in Sitecore in EditorMode.

How Can I do??

In Controller, this is what I'm thinking:

public class Components: SitecoreController
{
    public ActionResult testController()
    {
        if (submit clicks) {
            ComponentModel ob = new ComponentModel();
            ob.Initialize(RenderingContext.Current.Rendering);

            string selectedValue = selectedValue from View;

            ob.item.Editing.BeginEdit();
            using(new EditContext())
            {
                ob.CheckBoxField.Checked = (selectedValue == "True" ? true : false);
            }
            ob.item.Editing.EndEdit();
            return PartialView(ob);
        }

        return PartialView();
    }
}    

Upvotes: 2

Views: 2032

Answers (2)

Jay
Jay

Reputation: 1201

The issue has been resolved and I got exactly what I want to do by using Controller Rendering with Ajax.

I used DropList instead of Checkbox for checkbox field type.

Model

public class ComponentModel : IRenderingModel
{
    public string Title { get; set; }
    public Item Item { get; set; }
    public Item PageItem { get; set; }
    public Sitecore.Data.Fields.CheckboxField chBox { get; set; }
    ... some other declared data types based on templates if you want ...

    public void Initialize(Sitecore.Mvc.Presentation.Rendering rendering)
    {
        Rendering = rendering;
        Item = rendering.Item;
        PageItem = Sitecore.Mvc.Presentation.PageContext.Current.Item;

        Title = FieldRenderer.Render(Item, "Title");
        ... more if you want ...
    }
}

Controller

public class Components : Controller
{
    //
    // POST: /Components/

    public ActionResult ComponentView(string changedValue, string fieldName)
    {

        ComponentModel ss = new ComponentModel();
        ss.Initialize(RenderingContext.Current.Rendering);
        Item item = ss.Item;

        if (!String.IsNullOrEmpty(changedValue) && !String.IsNullOrEmpty(fieldName))
        {
            ss.Item.Editing.BeginEdit();
            using (new SecurityDisabler())
            {
                switch (fieldName)
                {
                    ... conditions ...
                }
            }
            ss.Item.Editing.EndEdit();
        }
        return PartialView(ss);
    }
}

View

@model yournamespace.ComponentModel
@using Sitecore.Mvc

@if (Sitecore.Context.PageMode.IsPageEditor)
{  
    if ([email protected](Model.Rendering.DataSource))
    {
        <div>No Associated Datasource.<br />Please Create New Datasource</div><br />
    }
    else
    {
        <div class="newdata">
            <h3>This is page editor</h3>
            Title: @Html.Raw(Model.Title) <br />

            DropList: <select name="list" id="fieldName" onclick="javascript:dlOnChangeUpdate('fieldName');">
                <option value="True" @Html.Raw((Model.chBox.Checked) ? "selected" : "")>Enable</option>
                <option value="False" @Html.Raw((!Model.chBox.Checked) ? "selected" : "")>Disable</option>
            </select><br />

            <script type="text/javascript">
                function dlOnChangeUpdate(fieldName)
                {
                    $("#" + fieldName).on('change', function () {
                        var changedValue = $("#" + fieldName).val();

                        $.ajax({
                            url: '@Url.Action("ComponentModel","Components")',
                            type: "POST",
                            data: { "changedValue": changedValue, "fieldName": fieldName },
                            context: this,
                            success: function (data) {
                                Sitecore.PageModes.PageEditor.postRequest('webedit:save()');
                                console.log("success", data);
                            },
                            error: function (data) {
                                alert('error: ' + data);
                                console.log("error", data);
                            }
                        });
                    });
                }
            </script>
        </div>
    }
}
else
{
    <div id="info">
        <h3>This is preview</h3>
    </div>
}

Upvotes: 1

xoail
xoail

Reputation: 3074

Try wrapping it in SecurityDisabler instead. Pseudo code:

public ActionResult testController()
{
    if (submit clicks) {
        ComponentModel ob = new ComponentModel();
        ob.Initialize(RenderingContext.Current.Rendering);

        string selectedValue = selectedValue from View;
        using(new SecurityDisabler()){
            var item = Sitecore.Data.Databases.GetDatabase("master");
            item.Editing.BeginEdit();

            item.Fields["CheckBoxField"].Value = (selectedValue == "True" ? true : false);
            item.Editing.EndEdit();
            item.SaveChanges();
        }
        return PartialView(ob);
    }

    return PartialView();
}

Upvotes: 0

Related Questions