Example #1
0
        protected void AddFunctions(ref IDictionary <string, object> htmlAttributes, bool chosen)
        {
            if (!chosen && htmlAttributes != null && htmlAttributes.ContainsKey("role-name"))
            {
                Role = htmlAttributes["role-name"] as string;
                htmlAttributes.Remove("role-name");
            }
            if (!chosen)
            {
                return;
            }
            if (functionWritten)
            {
                return;
            }
            if (htmlAttributes == null)
            {
                htmlAttributes = new Dictionary <string, object>();
            }
            if (Role != null)
            {
                htmlAttributes["role-name"] = Role;
                Role = null;
            }

            string id = BasicHtmlHelper.IdFromName(BasicHtmlHelper.AddField(this.totalPrefix, "$"));

            htmlAttributes["mvc-controls-toolkit-set"] =
                string.Format("function(x) {{MvcControlsToolkit_DateTime_Set('{0}', x);}}",
                              id);
            htmlAttributes["mvc-controls-toolkit-get-true"] =
                string.Format("MvcControlsToolkit_DateTime_GetTrue('{0}')",
                              id);
            functionWritten = true;
        }
Example #2
0
 private static void getPropertiesToUpdate(StringBuilder sb, string prefix, PropertyInfo[] propertiesToUpdate, Stack <Type> recursionControl)
 {
     for (int i = 0; i < propertiesToUpdate.Length; i++)
     {
         if (i > 0)
         {
             sb.Append(',');
         }
         if (typeof(IConvertible).IsAssignableFrom(propertiesToUpdate[i].PropertyType))
         {
             sb.Append(BasicHtmlHelper.IdFromName(BasicHtmlHelper.AddField(prefix, propertiesToUpdate[i].Name)));
         }
         else if (!typeof(System.Collections.IEnumerable).IsAssignableFrom(propertiesToUpdate[i].PropertyType))
         {
             bool recursion = false;
             foreach (Type type in recursionControl)
             {
                 if (type == propertiesToUpdate[i].PropertyType)
                 {
                     recursion = true;
                 }
             }
             if (recursion)
             {
                 continue;
             }
             recursionControl.Push(propertiesToUpdate[i].PropertyType);
             getPropertiesToUpdate(
                 sb,
                 BasicHtmlHelper.AddField(prefix, propertiesToUpdate[i].Name),
                 BasicHtmlHelper.GetPropertiesForInput(propertiesToUpdate[i].PropertyType), recursionControl);
             recursionControl.Pop();
         }
     }
 }
Example #3
0
        public static MvcHtmlString ManipulationButton <VM, T>(
            this HtmlHelper <VM> htmlHelper,
            ManipulationButtonType manipulationButtonType,
            string textOrUrl,
            Expression <Func <VM, T> > target,
            string name = null,
            ManipulationButtonStyle manipulationButtonStyle = ManipulationButtonStyle.Button,
            IDictionary <string, object> htmlAttributes     = null)
        {
            if (target == null)
            {
                throw new ArgumentNullException("target");
            }
            string targetName = BasicHtmlHelper.IdFromName(htmlHelper.ViewData.TemplateInfo.GetFullHtmlFieldName(
                                                               ExpressionHelper.GetExpressionText(target)));

            return
                (ManipulationButton <VM>(
                     htmlHelper,
                     manipulationButtonType,
                     textOrUrl,
                     targetName,
                     name,
                     manipulationButtonStyle,
                     htmlAttributes));
        }
Example #4
0
        public static MvcHtmlString ViewsOnOff <M>(this HtmlHelper <M> htmlHelper, string groupName, bool initialOn)
        {
            if (groupName == null)
            {
                throw (new ArgumentNullException("groupName"));
            }
            string viewsOnOffScript = null;
            string partialName      = groupName + "_selection";
            string fullName         = htmlHelper.ViewData.TemplateInfo.GetFullHtmlFieldName(partialName);
            string fullId           = BasicHtmlHelper.IdFromName(fullName);

            switch (MvcEnvironment.Validation(htmlHelper))
            {
            case ValidationType.StandardClient: viewsOnOffScript = viewsOnOfScriptStandardClient; break;

            case ValidationType.UnobtrusiveClient: viewsOnOffScript = viewsOnOfScriptScriptUnobtrusiveClient; break;

            default: viewsOnOffScript = viewsOnOfScriptScriptNoClient; break;
            }
            ValueProviderResult vr = htmlHelper.ViewContext.Controller.ValueProvider.GetValue(fullName);

            if (vr != null)
            {
                initialOn = (bool)(vr.ConvertTo(typeof(bool)));
            }
            return(MvcHtmlString.Create(
                       htmlHelper.Hidden(partialName, initialOn) +
                       string.Format(viewsOnOffScript, groupName, initialOn ? "true":"false", fullId)
                       ));
        }
Example #5
0
        public static MvcHtmlString GenericInputFor <VM, T>(
            this HtmlHelper <VM> htmlHelper,
            InputType inputType,
            Expression <Func <VM, T> > expression)
        {
            if (expression == null)
            {
                throw (new ArgumentNullException("expression"));
            }

            var name =
                htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(
                    ExpressionHelper.GetExpressionText(expression));
            string type  = GetInputTypeString(inputType);
            T      value = default(T);

            try
            {
                value = expression.Compile().Invoke(htmlHelper.ViewData.Model);
            }
            catch { }

            return(MvcHtmlString.Create(
                       string.Format("<input type='{3}' name='{0}' id='{1}' value='{2}' />",
                                     name, BasicHtmlHelper.IdFromName(name),
                                     htmlHelper.Encode(Convert.ToString(value, CultureInfo.InvariantCulture)),
                                     type)));
        }
Example #6
0
 internal string Render(string name)
 {
     return(string.Format(script, BasicHtmlHelper.IdFromName(name),
                          Animated,
                          Unique ? "true": "false",
                          javascriptPersitency()
                          ));
 }
Example #7
0
        public static MvcHtmlString ViewList <M>(
            this HtmlHelper <M> htmlHelper,
            string groupName,
            string cssSelected,
            string selection = null)
        {
            if (groupName == null)
            {
                throw (new ArgumentNullException("groupName"));
            }
            string partialName = groupName + "_selection";
            string fullId      = BasicHtmlHelper.IdFromName(htmlHelper.ViewData.TemplateInfo.GetFullHtmlFieldName(partialName));

            string viewSelectionScript = null;

            switch (MvcEnvironment.Validation(htmlHelper))
            {
            case ValidationType.StandardClient: viewSelectionScript = viewSelectionScriptStandardClient; break;

            case ValidationType.UnobtrusiveClient: viewSelectionScript = viewSelectionScriptUnobtrusiveClient; break;

            default: viewSelectionScript = viewSelectionScriptNoClient; break;
            }

            if (string.IsNullOrWhiteSpace(selection))
            {
                selection = string.Empty;
            }
            string prefix = htmlHelper.ViewData.TemplateInfo.HtmlFieldPrefix;

            if (string.IsNullOrWhiteSpace(prefix))
            {
                prefix = string.Empty;
            }
            else
            {
                prefix = BasicHtmlHelper.IdFromName(prefix) + "_";
            }
            ValueProviderResult vr =
                htmlHelper.ViewContext.Controller.ValueProvider.GetValue(htmlHelper.ViewData.TemplateInfo.GetFullHtmlFieldName(partialName));

            if (vr != null)
            {
                string oldres = vr.ConvertTo(typeof(string)) as string;
                if (!string.IsNullOrWhiteSpace(oldres))
                {
                    selection = oldres;
                }
            }
            if (string.IsNullOrWhiteSpace(cssSelected))
            {
                cssSelected = string.Empty;
            }
            return
                (MvcHtmlString.Create(
                     htmlHelper.Hidden(partialName, selection) +
                     string.Format(viewSelectionScript, groupName, fullId, selection, cssSelected, prefix)));
        }
Example #8
0
        public static MvcHtmlString ViewListFor <M>(
            this HtmlHelper <M> htmlHelper,
            Expression <Func <M, string> > expression,
            string groupName,
            string cssSelected)
        {
            if (expression == null)
            {
                throw (new ArgumentNullException("expression"));
            }
            if (groupName == null)
            {
                throw (new ArgumentNullException("groupName"));
            }

            string viewSelectionScript = null;

            switch (MvcEnvironment.Validation(htmlHelper))
            {
            case ValidationType.StandardClient: viewSelectionScript = viewSelectionScriptStandardClient; break;

            case ValidationType.UnobtrusiveClient: viewSelectionScript = viewSelectionScriptUnobtrusiveClient; break;

            default: viewSelectionScript = viewSelectionScriptNoClient; break;
            }

            string partialName = ExpressionHelper.GetExpressionText(expression);
            string fullId      = BasicHtmlHelper.IdFromName(htmlHelper.ViewData.TemplateInfo.GetFullHtmlFieldName(partialName));

            string selection = string.Empty;

            try
            {
                selection = expression.Compile().Invoke(htmlHelper.ViewData.Model) as string;
            }
            catch
            {
            }
            string prefix = htmlHelper.ViewData.TemplateInfo.HtmlFieldPrefix;

            if (string.IsNullOrWhiteSpace(prefix))
            {
                prefix = string.Empty;
            }
            else
            {
                prefix = BasicHtmlHelper.IdFromName(prefix) + "_";
            }
            if (string.IsNullOrWhiteSpace(cssSelected))
            {
                cssSelected = string.Empty;
            }
            return
                (MvcHtmlString.Create(
                     htmlHelper.Hidden(partialName, selection) +
                     string.Format(viewSelectionScript, groupName, fullId, selection, cssSelected, prefix)));
        }
Example #9
0
        public static MvcHtmlString TreeViewToggleEditButtonFor <VM, T>(
            this HtmlHelper <VM> htmlHelper,
            Expression <Func <VM, IEnumerable <T> > > expression,
            string textOrUrlEdit,
            string cssClassEdit,
            string textOrUrlUndoEdit,
            string cssClassUndoEdit,
            string textOrUrlRedoEdit,
            string cssClassRedoEdit,
            ManipulationButtonStyle manipulationButtonStyle = ManipulationButtonStyle.Button)
        {
            if (expression == null)
            {
                throw (new ArgumentNullException("expression"));
            }

            if (textOrUrlEdit == null)
            {
                throw (new ArgumentNullException("textOrUrlEdit"));
            }
            if (cssClassEdit == null)
            {
                throw (new ArgumentNullException("cssClassEdit"));
            }

            if (textOrUrlUndoEdit == null)
            {
                throw (new ArgumentNullException("textOrUrlUndoEdit"));
            }
            if (cssClassUndoEdit == null)
            {
                throw (new ArgumentNullException("cssClassUndoEdit"));
            }

            if (textOrUrlRedoEdit == null)
            {
                throw (new ArgumentNullException("textOrUrlRedoEdit"));
            }
            if (cssClassRedoEdit == null)
            {
                throw (new ArgumentNullException("cssClassRedoEdit"));
            }

            if (MvcEnvironment.Validation(htmlHelper) == ValidationType.StandardClient)
            {
                return(MvcHtmlString.Create(string.Empty));
            }
            string id = BasicHtmlHelper.IdFromName(htmlHelper.ViewData.TemplateInfo.GetFullHtmlFieldName(ExpressionHelper.GetExpressionText(expression)));

            return(MvcHtmlString.Create(
                       string.Format(initializeToggleEditButtonScript, id, textOrUrlEdit, cssClassEdit, textOrUrlUndoEdit, cssClassUndoEdit, textOrUrlRedoEdit, cssClassRedoEdit) +
                       htmlHelper.ManipulationButton(ManipulationButtonType.Custom, string.Empty,
                                                     string.Format(toggleEditButtonScript, id, textOrUrlEdit, cssClassEdit, textOrUrlUndoEdit, cssClassUndoEdit, textOrUrlRedoEdit, cssClassRedoEdit),
                                                     id + "_ToggleEditButton", manipulationButtonStyle, null).ToString()));
        }
Example #10
0
 private string pageString(int page)
 {
     if (page < 0)
     {
         return(string.Format("$('#{0}').val()||'{1}'", BasicHtmlHelper.IdFromName(htmlHelper.ViewData.TemplateInfo.GetFullHtmlFieldName(goTextName)), currPage));
     }
     else
     {
         return(string.Format("'{0}'", page));
     }
 }
Example #11
0
        protected string RenderBasicScripts(CultureInfo format)
        {
            if (baseScriptsRendered)
            {
                return(string.Empty);
            }
            baseScriptsRendered = true;

            StringBuilder sb = new StringBuilder();

            sb.Append(BasicHtmlHelper.RenderDisplayInfo(htmlHelper, this.GetType(), prefix));
            bool isClientBlock = htmlHelper.ViewData["ClientBindings"] != null ||
                                 htmlHelper.ViewContext.HttpContext.Items.Contains("ClientTemplateOn");

            sb.Append(string.Format(startScriptFormat,
                                    BasicHtmlHelper.IdFromName(BasicHtmlHelper.AddField(this.totalPrefix, "$")),
                                    BasicHtmlHelper.JavaScriptDate(min, isClientBlock),
                                    BasicHtmlHelper.JavaScriptDate(max, isClientBlock),
                                    clientOnChanged != null ? clientOnChanged + " return" : " return;",
                                    BasicHtmlHelper.JavaScriptDate(curr),
                                    clientMinScript,
                                    clientMaxScript,
                                    yearCombo ? "true" : "false",
                                    dateHidden ? "true" : "false",
                                    clientRefreshRegistrations,
                                    this.dateInCalendar ? "true" : "false",
                                    BasicHtmlHelper.GetAttributesString(attributeExtensions),
                                    totalPrefix
                                    ));
            sb.Append(BasicHtmlHelper.TrueValue(htmlHelper, this.totalPrefix, curr));
            FormatAttribute[] formatAttributes = pAccesor[typeof(FormatAttribute)] as FormatAttribute[];
            if (formatAttributes != null && formatAttributes.Length > 0)
            {
                sb.Append(BasicHtmlHelper.FormattedValueString(htmlHelper, this.totalPrefix, formatAttributes[0].HtmlEncode ? htmlHelper.Encode(formatAttributes[0].GetDisplay(curr)) : formatAttributes[0].GetDisplay(curr)));
            }
            else
            {
                DisplayFormatAttribute[] dFormatAttributes = pAccesor[typeof(DisplayFormatAttribute)] as DisplayFormatAttribute[];
                if (dFormatAttributes != null && dFormatAttributes.Length > 0)
                {
                    sb.Append(BasicHtmlHelper.FormattedValueString(htmlHelper, this.totalPrefix, dFormatAttributes[0].HtmlEncode ? htmlHelper.Encode(
                                                                       new FormatAttribute(dFormatAttributes[0]).GetDisplay(curr)) : new FormatAttribute(dFormatAttributes[0]).GetDisplay(curr)));
                }
            }
            if (format != null)
            {
                WriteMonthes(sb, format);
            }
            return(sb.ToString());
        }
Example #12
0
        protected void ComputeClientOnChanged()
        {
            string prefix = this.totalPrefix;

            if (constraints == null || constraints.Length == 0)
            {
                return;
            }
            StringBuilder sb           = new StringBuilder();
            string        fatherPrefix = BasicHtmlHelper.PreviousPrefix(prefix);

            foreach (DateRangeAttribute c in constraints)
            {
                c.RetriveDynamicDelays(htmlHelper.ViewData.Model, fatherPrefix);
                if (!string.IsNullOrWhiteSpace(c.DynamicMaximum) && c.RangeAction == RangeAction.Propagate)
                {
                    string controlId =
                        BasicHtmlHelper.IdFromName(
                            (fatherPrefix.Length != 0 ? fatherPrefix + "." + c.DynamicMaximum : c.DynamicMaximum) + ".$");
                    long delay = 0;
                    if (c.MaximumDelay != null && c.MaximumDelay.HasValue)
                    {
                        delay =
                            c.MaximumDelay.Value.Ticks / 10000L;
                    }
                    sb.Append(string.Format("SetDateInput('{0}', date - {1}, 2); ", controlId, delay));
                }
                if (!string.IsNullOrWhiteSpace(c.DynamicMinimum) && c.RangeAction == RangeAction.Propagate)
                {
                    string controlId =
                        BasicHtmlHelper.IdFromName(
                            (fatherPrefix.Length != 0 ? fatherPrefix + "." + c.DynamicMinimum : c.DynamicMinimum) + ".$");
                    long delay = 0;
                    if (c.MinimumDelay != null && c.MinimumDelay.HasValue)
                    {
                        delay =
                            c.MinimumDelay.Value.Ticks / 10000L;
                    }
                    sb.Append(string.Format("SetDateInput('{0}', date - {1}, 1); ", controlId, delay));
                }
            }
            clientOnChanged = sb.ToString();
        }
Example #13
0
        public ServerErrors(ModelStateDictionary origin, string prefix = null)
        {
            List <ServerError> res = new List <ServerError>();

            foreach (KeyValuePair <string, ModelState> pair in origin)
            {
                if (pair.Value.Errors.Count > 0 && (prefix == null || pair.Key.StartsWith(prefix)))
                {
                    res.Add(new ServerError
                    {
                        name   = pair.Key,
                        id     = BasicHtmlHelper.IdFromName(pair.Key),
                        errors = errorList(pair.Value)
                    });
                }
            }

            errors = res;
        }
Example #14
0
        public static MvcHtmlString GenericInput <VM>(
            this HtmlHelper <VM> htmlHelper,
            InputType inputType,
            string name,
            object value = null)
        {
            if (name == null)
            {
                throw (new ArgumentNullException("name"));
            }
            name =
                htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(
                    name);
            string type = GetInputTypeString(inputType);

            return(MvcHtmlString.Create(
                       string.Format("<input type='{3}' name='{0}' id='{1}' value='{2}' />",
                                     name, BasicHtmlHelper.IdFromName(name),
                                     htmlHelper.Encode(Convert.ToString(value, CultureInfo.InvariantCulture)),
                                     type)));
        }
Example #15
0
        public string FieldsToUpdate()
        {
            StringBuilder sb    = new StringBuilder();
            bool          first = true;

            sb.Append("'");
            foreach (LambdaExpression exp in Fields)
            {
                if (!first)
                {
                    sb.Append(',');
                }
                else
                {
                    first = false;
                }
                sb.Append(BasicHtmlHelper.IdFromName(ExpressionHelper.GetExpressionText(exp)));
            }
            sb.Append("'");
            return(sb.ToString());
        }
Example #16
0
        public ClientPager(HtmlHelper <VM> htmlHelper, string fieldName, int currPage, string totPagesFieldName, int?totPages, string pagePrefix, string pagePostfix, bool causeSubmit)
        {
            this.htmlHelper        = htmlHelper;
            this.currPage          = currPage;
            this.fieldName         = fieldName;
            this.fieldId           = BasicHtmlHelper.IdFromName(fieldName);
            this.totPages          = totPages;
            this.totPagesFieldName = totPagesFieldName;
            this.pageFieldRendered = false;
            this.pagePrefix        = pagePrefix;
            this.pagePostfix       = pagePostfix;
            goTextName             = fieldId + "_goto";
            this.causeSubmit       = causeSubmit;
            switch (MvcEnvironment.Validation(htmlHelper))
            {
            case ValidationType.StandardClient: validationType = "StandardClient"; break;

            case ValidationType.UnobtrusiveClient: validationType = "UnobtrusiveClient"; break;

            default: validationType = "Server"; break;
            }
        }
        public override string ToString()
        {
            if (namePrefix == null)
            {
                if (bindings != null)
                {
                    return(suitableTag.Replace(input, TagMatchEvaluator));
                }
                else
                {
                    return(scriptTag.Replace(input, scriptSubstitute));
                }
            }
            else
            {
                string res;

                if (string.IsNullOrWhiteSpace(namePrefix))
                {
                    res = suitableTag.Replace(input, TagMatchEvaluator).Replace(ClientTemplateHelper.templateSymbol + ".A.", string.Empty)
                          .Replace(ClientTemplateHelper.templateSymbol + "_A_", string.Empty);
                }
                else
                {
                    res = suitableTag.Replace(input, TagMatchEvaluator).Replace(ClientTemplateHelper.templateSymbol + ".A", namePrefix)
                          .Replace(ClientTemplateHelper.templateSymbol + "_A", BasicHtmlHelper.IdFromName(namePrefix));
                }
                if (addToBody != null)
                {
                    Match bodyTag = body.Match(res);
                    if (bodyTag.Success)
                    {
                        int split = bodyTag.Index + bodyTag.Length;
                        res = string.Format("{0} {1} {2}", res.Substring(0, split), addToBody, res.Substring(split));
                    }
                }
                return(res);
            }
        }
        public static MvcHtmlString SortableListAddButtonFor <VM, TItem>(
            this HtmlHelper <VM> htmlHelper,
            RenderInfo <IEnumerable <TItem> > renderInfo,
            string textOrUrl,
            ManipulationButtonStyle manipulationButtonStyle = ManipulationButtonStyle.Button,
            IDictionary <string, object> htmlAttributes     = null,
            string name       = null,
            int templateIndex = 0)
        {
            if (renderInfo == null)
            {
                throw (new ArgumentNullException("renderInfo"));
            }
            if (MvcEnvironment.Validation(htmlHelper) == ValidationType.StandardClient)
            {
                return(MvcHtmlString.Create(string.Empty));
            }
            string id = BasicHtmlHelper.IdFromName(renderInfo.Prefix);

            return(htmlHelper.ManipulationButton(ManipulationButtonType.Custom, textOrUrl,
                                                 string.Format(addButtonScript, id, templateIndex), name == null ? id + "_AddButton" + templateIndex.ToString(CultureInfo.InvariantCulture) : name, manipulationButtonStyle, htmlAttributes));
        }
        public static MvcHtmlString SortableListAddButtonFor <VM, T>(
            this HtmlHelper <VM> htmlHelper,
            Expression <Func <VM, IEnumerable <T> > > expression,
            string textOrUrl,
            ManipulationButtonStyle manipulationButtonStyle = ManipulationButtonStyle.Button,
            IDictionary <string, object> htmlAttributes     = null,
            string name       = null,
            int templateIndex = 0)
        {
            if (expression == null)
            {
                throw (new ArgumentNullException("expression"));
            }
            if (MvcEnvironment.Validation(htmlHelper) == ValidationType.StandardClient)
            {
                return(MvcHtmlString.Create(string.Empty));
            }
            string id = BasicHtmlHelper.IdFromName(htmlHelper.ViewData.TemplateInfo.GetFullHtmlFieldName(ExpressionHelper.GetExpressionText(expression)));

            return(htmlHelper.ManipulationButton(ManipulationButtonType.Custom, textOrUrl,
                                                 string.Format(addButtonScript, id, templateIndex), name == null ? id + "_AddButton" + templateIndex.ToString(CultureInfo.InvariantCulture) : name, manipulationButtonStyle, htmlAttributes));
        }
Example #20
0
 protected string RenderPageField()
 {
     if (pageFieldRendered)
     {
         return(string.Empty);
     }
     pageFieldRendered = true;
     if (prevPage != null && prevPage.HasValue)
     {
         string res = string.Format(@"<input type='hidden' value='{0}' id='{1}' name='{2}' /><input type='hidden' value='{3}' id='{4}'  name='{5}'/>",
                                    prevPage.Value, BasicHtmlHelper.IdFromName(prevFieldName), prevFieldName, currPage, BasicHtmlHelper.IdFromName(fieldName), fieldName);
         // htmlHelper.Hidden(prevFieldName, prevPage.Value).ToString() + htmlHelper.Hidden(fieldName, currPage).ToString();
         return(res);
     }
     else if (!string.IsNullOrEmpty(fieldName))
     {
         return
             (string.Format(@"<input type='hidden' value='{0}' id='{1}'  name='{2}'/>", currPage, BasicHtmlHelper.IdFromName(fieldName), fieldName));
     }
     else
     {
         return(string.Empty);
     }
 }
Example #21
0
        public string VerifyFieldsValid <F>(
            Expression <Func <M, F> > expression,
            params LambdaExpression[] otherExpressions)
        {
            if (writer == null)
            {
                return(string.Empty);
            }
            string firstParam =
                string.Format(
                    " if(!MvcControlsToolkit_Validate('{0}', '{1}')) return; ",
                    BasicHtmlHelper.IdFromName(GetFullName(expression)),
                    validationType);

            if (otherExpressions != null && otherExpressions.Length > 0)
            {
                StringBuilder sb = new StringBuilder();
                sb.Append(firstParam);
                foreach (LambdaExpression expr in otherExpressions)
                {
                    sb.Append(
                        string.Format(
                            " if(!MvcControlsToolkit_Validate('{0}', '{1}')) return; ",
                            BasicHtmlHelper.IdFromName(BasicHtmlHelper.AddField(
                                                           modelPrefix,
                                                           ExpressionHelper.GetExpressionText(expr))),
                            validationType)
                        );
                }
                return(sb.ToString());
            }
            else
            {
                return(firstParam);
            }
        }
Example #22
0
        private static void TreeViewTop <VM, T>(
            StringBuilder sb,
            bool editMode,
            HtmlHelper <VM> htmlHelper,
            RenderInfo <IEnumerable <T> > renderInfo,
            Func <int, string> collectionName,
            ExternalContainerType itemContainer,
            string rootClass,
            object[] itemTemplates,
            Func <object, int, int> itemTemplateSelector,
            Func <int, string> itemClassSelector,
            Func <object, int, TreeViewItemStatus> itemStatus,
            float opacity,
            bool canMove,
            bool canAdd,
            TreeViewOptions treeViewOptions)
        {
            if (rootClass == null)
            {
                rootClass = defaultRootClass;
            }


            RenderInfo <TreeViewDisplay <T> > branchesRenderInfo = htmlHelper.InvokeTransform(renderInfo, new TreeViewDisplay <T>());

            if (editMode)
            {
                sb.Append(branchesRenderInfo.PartialRendering);
            }

            renderInfo.Prefix        = BasicHtmlHelper.AddField(branchesRenderInfo.Prefix, "flattened");
            renderInfo.PartialPrefix = BasicHtmlHelper.AddField(branchesRenderInfo.PartialPrefix, "flattened");

            StringBuilder sbInit = new StringBuilder();

            sbInit.Append(treeViewOptions.Render(renderInfo.Prefix));
            string basic_id = BasicHtmlHelper.IdFromName(renderInfo.Prefix);
            int    res      = TreeViewRec <VM, T>(
                sb,
                sbInit,
                editMode,
                htmlHelper,
                renderInfo,
                collectionName,
                itemContainer,
                rootClass,
                itemTemplates,
                itemTemplateSelector,
                itemClassSelector,
                itemStatus,
                opacity,
                canMove,
                0,
                0,
                basic_id,
                basic_id);

            if (canAdd)
            {
                StringBuilder templatesId      = new StringBuilder();
                string        myTemplateSymbol = BasicHtmlHelper.GetUniqueSymbol(htmlHelper, templateSymbol);
                sb.AppendFormat("<div id='{0}_Templates'>", basic_id);
                int templateIndex = -1;
                IDictionary <string, object> htmlAttributesContainer = new Dictionary <string, object>();
                foreach (object template in itemTemplates)
                {
                    templateIndex++;
                    Type type = TemplateInvoker <string> .ExtractModelType(template);

                    string initCollection = collectionName(templateIndex);

                    ITreeViewNodeContainer wrapper =
                        typeof(TreeViewUpdater <string>).GetGenericTypeDefinition()
                        .MakeGenericType(new Type[] { type })
                        .GetConstructor(new Type[0])
                        .Invoke(new object[0]) as ITreeViewNodeContainer;


                    bool closed = false;
                    (wrapper as IUpdateModel).ImportFromModel(null, null, null, new object[] { closed });

                    string prefix        = renderInfo.Prefix;
                    string partialPrefix = renderInfo.PartialPrefix;
                    string updater       = BasicHtmlHelper.RenderUpdateInfoI(
                        htmlHelper, wrapper as IUpdateModel,
                        ref partialPrefix, new string[0], myTemplateSymbol + templateIndex.ToString());

                    prefix = htmlHelper.ViewData.TemplateInfo.GetFullHtmlFieldName(partialPrefix);



                    wrapper.FatherOriginalId  = string.Empty;
                    wrapper.OriginalId        = prefix;
                    wrapper.PositionAsSon     = 0;
                    wrapper.SonNumber         = 0;
                    wrapper.SonCollectionName = initCollection;
                    wrapper.Closed            = false;
                    string itemOpenTag  = null;
                    string itemCloseTag = null;

                    string innerItemOpenTag  = null;
                    string innerItemCloseTag = null;

                    string templateId       = BasicHtmlHelper.IdFromName(BasicHtmlHelper.AddField(prefix, "Container"));
                    string templateUniqueId = templateId + templateIndex.ToString();
                    addTemplateId(templatesId, templateUniqueId);
                    htmlAttributesContainer["id"]    = templateId;
                    htmlAttributesContainer["class"] = closed ? "closed" : "open";
                    BasicHtmlHelper.GetContainerTags(ExternalContainerType.li, htmlAttributesContainer, out itemOpenTag, out itemCloseTag);

                    htmlAttributesContainer["id"]    = BasicHtmlHelper.IdFromName(BasicHtmlHelper.AddField(prefix, "$.Item_SubContainer"));
                    htmlAttributesContainer["class"] = string.Empty;
                    BasicHtmlHelper.GetContainerTags(itemContainer, htmlAttributesContainer, out innerItemOpenTag, out innerItemCloseTag);

                    bool hasCollection = true;

                    PropertyInfo property = null;
                    if (initCollection == null)
                    {
                        hasCollection = false;
                    }
                    else
                    {
                        property      = type.GetProperty(initCollection);
                        hasCollection = typeof(IEnumerable).IsAssignableFrom(property.PropertyType);
                    }
                    sb.Append(string.Format("<span id='{0}' style='display:none' class='MVCCT_EncodedTemplate'>", templateUniqueId));
                    StringBuilder itemSb = new StringBuilder();
                    itemSb.Append(itemOpenTag);

                    if (canMove && hasCollection)
                    {
                        itemSb.Append(string.Format("<input  type='checkbox' class ='level-select_{0} level-select' />", basic_id));
                    }
                    itemSb.Append(innerItemOpenTag);

                    itemSb.Append(
                        (typeof(TemplateInvoker <string>)
                         .GetGenericTypeDefinition()
                         .MakeGenericType(new Type[] { type })
                         .GetConstructor(new Type[] { typeof(object) })
                         .Invoke(new object[] { template }) as ITemplateInvoker)
                        .Invoke(htmlHelper, null, BasicHtmlHelper.AddField(prefix, "$.Item")));
                    itemSb.Append(innerItemCloseTag);

                    itemSb.Append(string.Format("<span class= 'MvcCT_init_info_{0}'>", basic_id));
                    itemSb.Append(updater);
                    RenderWrapper <VM>(htmlHelper, partialPrefix, wrapper, itemSb);
                    itemSb.Append("</span>");

                    if (hasCollection)
                    {
                        string base_id       = BasicHtmlHelper.IdFromName(prefix);
                        string currItemClass = itemClassSelector == null ?
                                               null :
                                               itemClassSelector(templateIndex);
                        if (currItemClass != null)
                        {
                            currItemClass = currItemClass + "_" + basic_id;
                        }
                        else
                        {
                            currItemClass = string.Empty;
                        }
                        string externalOpenTag  = null;
                        string externalCloseTag = null;
                        htmlAttributesContainer["id"] = base_id + "_ItemsContainer";

                        htmlAttributesContainer["class"] = currItemClass + " mvcct-items-container";

                        BasicHtmlHelper.GetContainerTags(ExternalContainerType.ul, htmlAttributesContainer, out externalOpenTag, out externalCloseTag);

                        itemSb.Append(externalOpenTag);
                        itemSb.Append(externalCloseTag);
                        if (canMove)
                        {
                            string javasctiptOpacity = string.Empty;
                            if (opacity > 1f)
                            {
                                opacity = 1f;
                            }
                            else if (opacity < 0.01f)
                            {
                                opacity = 0.01f;
                            }

                            if (opacity < 1f)
                            {
                                javasctiptOpacity = string.Format(" opacity: {0}, ", opacity.ToString(CultureInfo.InvariantCulture));
                            }
                            string javascriptRootClass = string.Empty;
                            if (currItemClass != null)
                            {
                                javascriptRootClass = string.Format(" connectWith: '.{0}', ", currItemClass);
                            }

                            itemSb.Append(string.Format(startScriptFormat,
                                                        base_id,
                                                        javasctiptOpacity,
                                                        javascriptRootClass,
                                                        basic_id));
                        }
                    }
                    itemSb.Append(itemCloseTag);
                    sb.Append(htmlHelper.Encode(itemSb.ToString()));
                    sb.Append("</span>");
                }
                sb.Append("</div>");
                sb.AppendFormat(
                    startTemplateScriptFormat,
                    basic_id, canMove ? "true" : "false",
                    myTemplateSymbol,
                    templatesId.ToString());
            }
            if (editMode)
            {
                sbInit.Append(htmlHelper.Hidden(BasicHtmlHelper.AddField(renderInfo.PartialPrefix, "$.ItemsCount"),
                                                res).ToString());
            }
            if (canMove)
            {
                sbInit.Append(string.Format(levelSelection, basic_id));
            }
            sb.Append(sbInit.ToString());
        }
        public static MvcHtmlString SortableListFor <VM, TItem>(
            this HtmlHelper <VM> htmlHelper,
            RenderInfo <IEnumerable <TItem> > renderInfo,
            object template,
            object addElementTemplate = null,
            float opacity             = 1,
            bool canSort = true,
            IDictionary <string, object> htmlAttributesContainer = null,
            IDictionary <string, object> htmlAttributesItems     = null,
            bool enableMultipleInsert               = true,
            ExternalContainerType itemContainer     = ExternalContainerType.li,
            ExternalContainerType allItemsContainer = ExternalContainerType.ul,
            object headerTemplate = null,
            object footerTemplate = null,
            string itemCss        = null,
            string altItemCss     = null,
            bool displayOnly      = false,
            string sortableHandle = null,
            Func <TItem, int> templateSelector = null,
            Func <int, IDictionary <string, object> > htmlAttributesSelector = null
            )
        {
            if (template == null)
            {
                throw (new ArgumentNullException("template"));
            }
            if (renderInfo == null)
            {
                throw (new ArgumentNullException("renderiNFO"));
            }
            if (string.IsNullOrWhiteSpace(itemCss))
            {
                itemCss = string.Empty;
            }
            if (string.IsNullOrWhiteSpace(altItemCss))
            {
                altItemCss = string.Empty;
            }
            if (displayOnly)
            {
                canSort = false;
            }
            if (canSort)
            {
                itemContainer     = ExternalContainerType.li;
                allItemsContainer = ExternalContainerType.ul;
                headerTemplate    = null;
                footerTemplate    = null;
                htmlHelper.ViewData[renderInfo.Prefix + "_Rendering"] = "SortableList_Dragging";
            }
            else
            {
                htmlHelper.ViewData[renderInfo.Prefix + "_Rendering"] = "SortableList_Dragging";
            }
            bool multipleTemplates = false;

            if (template is string || !(template is object[]))
            {
                template = new object[] { template };
            }
            else if (templateSelector != null)
            {
                multipleTemplates = true;
            }
            int nTemplates = (template as object[]).Length;

            Type[] allTypes = new Type[nTemplates];
            int    tcount   = 0;

            foreach (object t in (template as object[]))
            {
                if (t is string)
                {
                    allTypes[tcount] = typeof(TItem);
                }
                else
                {
                    allTypes[tcount] = TemplateInvoker <string> .ExtractModelType(t);
                }
                tcount++;
            }
            StringBuilder sb     = new StringBuilder();
            StringBuilder sbInit = new StringBuilder();

            sbInit.Append(renderInfo.PartialRendering);
            if (htmlAttributesContainer == null)
            {
                htmlAttributesContainer = new Dictionary <string, object>();
            }
            htmlAttributesContainer["id"] = BasicHtmlHelper.IdFromName(renderInfo.Prefix) + "_ItemsContainer";
            string externalOpenTag  = null;
            string externalCloseTag = null;
            string itemOpenTag      = null;
            string itemCloseTag     = null;

            BasicHtmlHelper.GetContainerTags(allItemsContainer, htmlAttributesContainer, out externalOpenTag, out externalCloseTag);
            sb.Append(externalOpenTag);

            if (htmlAttributesItems == null)
            {
                htmlAttributesItems = new Dictionary <string, object>();
            }
            IDictionary <string, object> fixedHtmlAttributesItems = htmlAttributesItems;
            bool   templateEnabled     = false;
            string addItemScriptFormat = addItemJQueryScriptFormat;

            switch (MvcEnvironment.Validation(htmlHelper))
            {
            case ValidationType.StandardClient:  break;

            case ValidationType.UnobtrusiveClient:  templateEnabled = true; break;

            default:  templateEnabled = true; break;
            }

            templateEnabled = templateEnabled && enableMultipleInsert;
            int    totalCount               = 0;
            string javasctiptOpacity        = string.Empty;
            string javascriptHandle         = string.Empty;
            string permutationElementPrefix = null;

            if (renderInfo.Model == null)
            {
                renderInfo.Model = new List <TItem>();
            }
            if (renderInfo.Model != null)
            {
                if (headerTemplate != null)
                {
                    if (multipleTemplates)
                    {
                        htmlAttributesItems = dictionarySelection(htmlAttributesSelector, fixedHtmlAttributesItems, -1);
                    }
                    ViewDataDictionary <TItem> dataDictionary = new ViewDataDictionary <TItem>();
                    dataDictionary.TemplateInfo.HtmlFieldPrefix = renderInfo.Prefix;
                    if (htmlHelper.ViewData.ContainsKey("ThemeParams"))
                    {
                        dataDictionary["ThemeParams"] = htmlHelper.ViewData["ThemeParams"];
                    }
                    BasicHtmlHelper.CopyRelevantErrors(dataDictionary.ModelState, htmlHelper.ViewData.ModelState, dataDictionary.TemplateInfo.HtmlFieldPrefix);
                    htmlAttributesItems["id"] = BasicHtmlHelper.IdFromName(BasicHtmlHelper.AddField(renderInfo.Prefix, "Header"));
                    BasicHtmlHelper.GetContainerTags(itemContainer, htmlAttributesItems, out itemOpenTag, out itemCloseTag);
                    sb.Append(itemOpenTag);
                    sb.Append(new TemplateInvoker <TItem>(headerTemplate).Invoke <VM>(htmlHelper, dataDictionary));
                    sb.Append(itemCloseTag);
                }
                foreach (TItem x in renderInfo.Model)
                {
                    if (x == null && htmlHelper.ViewContext.ViewData.ModelState.IsValid)
                    {
                        continue;
                    }
                    totalCount++;
                    int  templateIndex = 0;
                    Type currType      = typeof(TItem);
                    if (multipleTemplates)
                    {
                        templateIndex       = templateSelector(x);
                        currType            = allTypes[templateIndex];
                        htmlAttributesItems = dictionarySelection(htmlAttributesSelector, fixedHtmlAttributesItems, templateIndex);
                    }
                    IUpdateModel um = null;
                    if (x == null)
                    {
                        um = typeof(AutoEnumerableUpdater <string>).GetGenericTypeDefinition().MakeGenericType(currType)
                             .GetConstructor(new Type[0]).Invoke(new object[0]) as IUpdateModel;
                    }
                    else if (x.GetType() == typeof(TItem))
                    {
                        um = new AutoEnumerableUpdater <TItem>();
                    }
                    else
                    {
                        um = typeof(AutoEnumerableUpdater <string>).GetGenericTypeDefinition().MakeGenericType(x.GetType())
                             .GetConstructor(new Type[0]).Invoke(new object[0]) as IUpdateModel;
                    }
                    um.ImportFromModel(x, null, null, new object[0]);
                    string prefix        = renderInfo.Prefix;
                    string partialPrefix = renderInfo.PartialPrefix;
                    string updateInfo    = BasicHtmlHelper.RenderUpdateInfo <TItem>(htmlHelper, um, ref partialPrefix, new string[0]);
                    if (!displayOnly)
                    {
                        sbInit.Append(updateInfo);
                    }
                    prefix = htmlHelper.ViewData.TemplateInfo.GetFullHtmlFieldName(partialPrefix);
                    object currTemplate = (template as object[])[templateIndex];

                    ViewDataDictionary dataDictionary = null;
                    ITemplateInvoker   currInvoker    = null;
                    if (allTypes[templateIndex] == typeof(TItem))
                    {
                        dataDictionary = new ViewDataDictionary <TItem>(x);
                        currInvoker    = new TemplateInvoker <TItem>(currTemplate);
                    }
                    else
                    {
                        dataDictionary = typeof(ViewDataDictionary <string>).GetGenericTypeDefinition().MakeGenericType(allTypes[templateIndex])
                                         .GetConstructor(new Type[] { allTypes[templateIndex] }).Invoke(new object[] { x }) as ViewDataDictionary;

                        currInvoker = typeof(TemplateInvoker <string>).GetGenericTypeDefinition().MakeGenericType(allTypes[templateIndex])
                                      .GetConstructor(new Type[] { typeof(object) }).Invoke(new object[] { currTemplate }) as ITemplateInvoker;
                    }
                    dataDictionary.TemplateInfo.HtmlFieldPrefix = BasicHtmlHelper.AddField(prefix, "$.Item");
                    if (htmlHelper.ViewData.ContainsKey("ThemeParams"))
                    {
                        dataDictionary["ThemeParams"] = htmlHelper.ViewData["ThemeParams"];
                    }
                    BasicHtmlHelper.CopyRelevantErrors(dataDictionary.ModelState, htmlHelper.ViewData.ModelState, dataDictionary.TemplateInfo.HtmlFieldPrefix);
                    htmlAttributesItems["id"] = BasicHtmlHelper.IdFromName(BasicHtmlHelper.AddField(prefix, "$.Item")) + "_Container";
                    BasicHtmlHelper.GetContainerTags(itemContainer, htmlAttributesItems, out itemOpenTag, out itemCloseTag);
                    sb.Append(itemOpenTag);
                    sb.Append(currInvoker.Invoke <VM>(htmlHelper, dataDictionary));
                    sb.Append(itemCloseTag);
                }
            }
            string delayedRendering = null;

            if (addElementTemplate != null && !templateEnabled)
            {
                EnumerableUpdater <TItem> um = new EnumerableUpdater <TItem>(true);
                string prefix        = renderInfo.Prefix;
                string partialPrefix = renderInfo.PartialPrefix;
                sbInit.Append(
                    BasicHtmlHelper.RenderUpdateInfo <TItem>(htmlHelper, um, ref partialPrefix, new string[0]));
                prefix = htmlHelper.ViewData.TemplateInfo.GetFullHtmlFieldName(partialPrefix);
                sbInit.Append(htmlHelper.GenericInput(InputType.Hidden,
                                                      BasicHtmlHelper.AddField(partialPrefix, "$.Deleted"), um.Deleted, null));
                delayedRendering = string.Format(
                    addItemScriptFormat,
                    BasicHtmlHelper.IdFromName(BasicHtmlHelper.AddField(prefix, "$.Item.InnerContainer")));
                ViewDataDictionary <TItem> dataDictionary = new ViewDataDictionary <TItem>(um.Item);
                dataDictionary.TemplateInfo.HtmlFieldPrefix = BasicHtmlHelper.AddField(prefix, "$.Item");
                if (htmlHelper.ViewData.ContainsKey("ThemeParams"))
                {
                    dataDictionary["ThemeParams"] = htmlHelper.ViewData["ThemeParams"];
                }
                BasicHtmlHelper.CopyRelevantErrors(dataDictionary.ModelState, htmlHelper.ViewData.ModelState, dataDictionary.TemplateInfo.HtmlFieldPrefix);
                htmlAttributesItems["id"] = BasicHtmlHelper.IdFromName(BasicHtmlHelper.AddField(prefix, "$.Item")) + "_Container";

                BasicHtmlHelper.GetContainerTags(itemContainer, htmlAttributesItems, out itemOpenTag, out itemCloseTag);
                sb.Append(itemOpenTag);
                sb.Append(new TemplateInvoker <TItem>(addElementTemplate).Invoke <VM>(htmlHelper, dataDictionary));
                sb.Append(itemCloseTag);
            }
            if (canSort)
            {
                PermutationsUpdater <TItem> um = new PermutationsUpdater <TItem>();
                um.ImportFromModel(null, null, null, new object[0]);
                string prefix        = renderInfo.Prefix;
                string partialPrefix = renderInfo.PartialPrefix;
                sbInit.Append(
                    BasicHtmlHelper.RenderUpdateInfo <TItem>(htmlHelper, um, ref partialPrefix, new string[0]));
                prefix = htmlHelper.ViewData.TemplateInfo.GetFullHtmlFieldName(partialPrefix);
                sbInit.Append(
                    string.Format("<input type='hidden' id={0} name={1} value=''/>",
                                  BasicHtmlHelper.IdFromName(renderInfo.Prefix + "_Permutation"),
                                  BasicHtmlHelper.AddField(prefix, "$.Permutation")));
                if (opacity > 1f)
                {
                    opacity = 1f;
                }
                else if (opacity < 0.01f)
                {
                    opacity = 0.01f;
                }

                if (opacity < 1f)
                {
                    javasctiptOpacity = string.Format(" opacity: {0}, ", opacity.ToString(CultureInfo.InvariantCulture));
                }
                if (sortableHandle != null)
                {
                    javascriptHandle = string.Format(" handle: '{0}', ", sortableHandle);
                }
                permutationElementPrefix = prefix;
            }
            if (footerTemplate != null)
            {
                if (multipleTemplates)
                {
                    htmlAttributesItems = dictionarySelection(htmlAttributesSelector, fixedHtmlAttributesItems, -2);
                }
                ViewDataDictionary <TItem> dataDictionary = new ViewDataDictionary <TItem>();
                dataDictionary.TemplateInfo.HtmlFieldPrefix = renderInfo.Prefix;
                if (htmlHelper.ViewData.ContainsKey("ThemeParams"))
                {
                    dataDictionary["ThemeParams"] = htmlHelper.ViewData["ThemeParams"];
                }
                BasicHtmlHelper.CopyRelevantErrors(dataDictionary.ModelState, htmlHelper.ViewData.ModelState, dataDictionary.TemplateInfo.HtmlFieldPrefix);
                htmlAttributesItems["id"] = BasicHtmlHelper.IdFromName(BasicHtmlHelper.AddField(renderInfo.Prefix, "Footer"));
                BasicHtmlHelper.GetContainerTags(itemContainer, htmlAttributesItems, out itemOpenTag, out itemCloseTag);
                sb.Append(itemOpenTag);
                sb.Append(new TemplateInvoker <TItem>(footerTemplate).Invoke <VM>(htmlHelper, dataDictionary));
                sb.Append(itemCloseTag);
            }
            if (templateEnabled)
            {
                IUpdateModel  um                  = null;
                TItem         dummyItem           = default(TItem);
                object[]      allTemplates        = template as object[];
                StringBuilder alltemplateNames    = new StringBuilder();
                StringBuilder allhiddenNames      = new StringBuilder();
                StringBuilder allsymbolNames      = new StringBuilder();
                string        basicTemplateSymbol = BasicHtmlHelper.GetUniqueSymbol(htmlHelper, templateSymbol);
                for (int i = 0; i < allTemplates.Length; i++)
                {
                    if (multipleTemplates)
                    {
                        htmlAttributesItems = dictionarySelection(htmlAttributesSelector, fixedHtmlAttributesItems, i);
                    }
                    if (allTypes[i] == typeof(TItem))
                    {
                        um = new AutoEnumerableUpdater <TItem>();
                    }
                    else
                    {
                        um = typeof(AutoEnumerableUpdater <string>).GetGenericTypeDefinition().MakeGenericType(allTypes[i])
                             .GetConstructor(new Type[0]).Invoke(new object[0]) as IUpdateModel;
                    }
                    string prefix           = renderInfo.Prefix;
                    string partialPrefix    = renderInfo.PartialPrefix;
                    string myTemplateSymbol = basicTemplateSymbol + i.ToString(CultureInfo.InvariantCulture);

                    sbInit.Append(
                        BasicHtmlHelper.RenderUpdateInfoI(htmlHelper, um, ref partialPrefix, new string[0], myTemplateSymbol));
                    prefix = htmlHelper.ViewData.TemplateInfo.GetFullHtmlFieldName(partialPrefix);

                    ViewDataDictionary dataDictionary = null;
                    ITemplateInvoker   currInvoker    = null;
                    if (allTypes[i] == typeof(TItem))
                    {
                        dataDictionary = new ViewDataDictionary <TItem>(dummyItem);
                        currInvoker    = new TemplateInvoker <TItem>(allTemplates[i]);
                    }
                    else
                    {
                        dataDictionary = typeof(ViewDataDictionary <string>).GetGenericTypeDefinition().MakeGenericType(allTypes[i])
                                         .GetConstructor(new Type[] { allTypes[i] }).Invoke(new object[] { dummyItem }) as ViewDataDictionary;

                        currInvoker = typeof(TemplateInvoker <string>).GetGenericTypeDefinition().MakeGenericType(allTypes[i])
                                      .GetConstructor(new Type[] { typeof(object) }).Invoke(new object[] { allTemplates[i] }) as ITemplateInvoker;
                    }

                    dataDictionary.TemplateInfo.HtmlFieldPrefix = BasicHtmlHelper.AddField(prefix, "$.Item");
                    if (htmlHelper.ViewData.ContainsKey("ThemeParams"))
                    {
                        dataDictionary["ThemeParams"] = htmlHelper.ViewData["ThemeParams"];
                    }
                    BasicHtmlHelper.CopyRelevantErrors(dataDictionary.ModelState, htmlHelper.ViewData.ModelState, dataDictionary.TemplateInfo.HtmlFieldPrefix);


                    string templateId = BasicHtmlHelper.IdFromName(BasicHtmlHelper.AddField(prefix, "$.Item")) + "_Container";
                    htmlAttributesItems["id"] = templateId;
                    if (i > 0)
                    {
                        alltemplateNames.Append(", ");
                        allhiddenNames.Append(", ");
                        allsymbolNames.Append(", ");
                    }
                    alltemplateNames.Append("'");
                    alltemplateNames.Append(templateId);
                    alltemplateNames.Append("'");

                    allhiddenNames.Append("'");
                    allhiddenNames.Append(BasicHtmlHelper.IdFromName(prefix));
                    allhiddenNames.Append("'");

                    allsymbolNames.Append("/");
                    allsymbolNames.Append(myTemplateSymbol);
                    allsymbolNames.Append("/g");

                    BasicHtmlHelper.GetContainerTags(itemContainer, htmlAttributesItems, out itemOpenTag, out itemCloseTag);
                    sb.Append(string.Format("<span id='{0}' style='display:none' class='MVCCT_EncodedTemplate'>", templateId));
                    sb.Append(htmlHelper.Encode(itemOpenTag));
                    sb.Append(htmlHelper.Encode(currInvoker.Invoke <VM>(htmlHelper, dataDictionary)));
                    sb.Append(htmlHelper.Encode(itemCloseTag));
                    sb.Append("</span>");
                }

                sbInit.Append(string.Format(startTemplateScriptFormat, BasicHtmlHelper.IdFromName(renderInfo.Prefix),
                                            canSort ? "true" : "false", totalCount, allsymbolNames.ToString(), alltemplateNames.ToString(),
                                            allhiddenNames.ToString(), renderInfo.Prefix));
            }

            if (canSort)
            {
                sbInit.Append(string.Format(startScriptFormat, BasicHtmlHelper.IdFromName(renderInfo.Prefix), javascriptHandle + javasctiptOpacity, BasicHtmlHelper.IdFromName(permutationElementPrefix)));
            }
            string stylingJavaScript = string.Format(stylingScript, BasicHtmlHelper.IdFromName(renderInfo.Prefix), itemCss, altItemCss);

            sbInit.Append(stylingJavaScript);
            if (delayedRendering != null)
            {
                sbInit.Append(delayedRendering);
            }
            sb.Append(externalCloseTag);
            sbInit.Insert(0, sb.ToString());
            return(MvcHtmlString.Create(sbInit.ToString()));
        }
Example #24
0
        public static MvcHtmlString ManipulationButton <VM>(
            this HtmlHelper <VM> htmlHelper,
            ManipulationButtonType manipulationButtonType,
            string textOrUrl,
            string targetName,
            string name = null,
            ManipulationButtonStyle manipulationButtonStyle = ManipulationButtonStyle.Button,
            IDictionary <string, object> htmlAttributes     = null)
        {
            if (string.IsNullOrWhiteSpace(name))
            {
                name = getManipulationButtonClass(manipulationButtonType);
            }
            if (textOrUrl == null)
            {
                throw new ArgumentNullException("textOrUrl");
            }
            if (targetName == null)
            {
                throw new ArgumentNullException("targetName");
            }

            if (htmlAttributes == null)
            {
                htmlAttributes = new Dictionary <string, object>();
            }

            string buttonId = BasicHtmlHelper.IdFromName(
                BasicHtmlHelper.AddField(htmlHelper.ViewData.TemplateInfo.HtmlFieldPrefix, name));

            htmlAttributes["id"] = buttonId;
            switch (manipulationButtonStyle)
            {
            case ManipulationButtonStyle.Button:
                htmlAttributes["type"]  = "button";
                htmlAttributes["value"] = htmlHelper.Encode(textOrUrl);
                return(MvcHtmlString.Create(
                           string.Format(buttonSchema,
                                         BasicHtmlHelper.GetAttributesString(htmlAttributes),
                                         processTarget(manipulationButtonType, targetName),
                                         getManipulationButtonClass(manipulationButtonType),
                                         buttonId)));

            case ManipulationButtonStyle.Link:
                htmlAttributes["href"] = "javascript:void(0);";
                return(MvcHtmlString.Create(
                           string.Format(linkSchema,
                                         BasicHtmlHelper.GetAttributesString(htmlAttributes),
                                         processTarget(manipulationButtonType, targetName),
                                         getManipulationButtonClass(manipulationButtonType),
                                         buttonId,
                                         htmlHelper.Encode(textOrUrl))));

            default:
                htmlAttributes["src"] = textOrUrl;
                BasicHtmlHelper.SetDefaultStyle(htmlAttributes, "cursor", "pointer");
                return(MvcHtmlString.Create(
                           string.Format(imgSchema,
                                         BasicHtmlHelper.GetAttributesString(htmlAttributes),
                                         processTarget(manipulationButtonType, targetName),
                                         getManipulationButtonClass(manipulationButtonType),
                                         buttonId)));
            }
        }/*
Example #25
0
        protected void GetItemContainerTags(
            ItemContainerType itemContainerType,
            int index,
            Func <TItem, int, string> getDynamicContainer,
            IDictionary <string, object> htmlattributes,
            string prefix,
            bool hidden,
            out string openTag,
            out string closureTag
            )
        {
            if (htmlattributes == null)
            {
                htmlattributes = new Dictionary <string, object>();
            }
            BasicHtmlHelper.SetAttribute(htmlattributes, "id", BasicHtmlHelper.IdFromName(prefix) + "_Container");

            if (hidden)
            {
                BasicHtmlHelper.SetDefaultStyle(htmlattributes, "display", "none");
            }
            switch (itemContainerType)
            {
            case ItemContainerType.div:
                openTag    = string.Format("<div {0}>", BasicHtmlHelper.GetAttributesString(htmlattributes));
                closureTag = "</div>";
                break;

            case ItemContainerType.span:
                openTag    = string.Format("<span {0}>", BasicHtmlHelper.GetAttributesString(htmlattributes));
                closureTag = "</span>";
                break;

            case ItemContainerType.tr:
                openTag    = string.Format("<tr {0}>", BasicHtmlHelper.GetAttributesString(htmlattributes));
                closureTag = "</tr>";
                break;

            case ItemContainerType.td:
                openTag    = string.Format("<td {0}>", BasicHtmlHelper.GetAttributesString(htmlattributes));
                closureTag = "</td>";
                break;

            case ItemContainerType.li:
                openTag    = string.Format("<li {0}>", BasicHtmlHelper.GetAttributesString(htmlattributes));
                closureTag = "</li>";
                break;

            case ItemContainerType.section:
                openTag    = string.Format("<section {0}>", BasicHtmlHelper.GetAttributesString(htmlattributes));
                closureTag = "</section>";
                break;

            case ItemContainerType.article:
                openTag    = string.Format("<article {0}>", BasicHtmlHelper.GetAttributesString(htmlattributes));
                closureTag = "</article>";
                break;

            case ItemContainerType.p:
                openTag    = string.Format("<p {0}>", BasicHtmlHelper.GetAttributesString(htmlattributes));
                closureTag = "</p>";
                break;

            default:
                if (getDynamicContainer != null)
                {
                    string tagName = getDynamicContainer(Item.OldValue, index);
                    openTag    = string.Format("<{1} {0}>", BasicHtmlHelper.GetAttributesString(htmlattributes), tagName);
                    closureTag = string.Format("</{0}>", tagName);
                }
                else
                {
                    openTag    = string.Format("<div {0}>", BasicHtmlHelper.GetAttributesString(htmlattributes));
                    closureTag = "</div>";
                }
                break;
            }
        }
Example #26
0
        public static IBindingsBuilder <T> Template <T, F>(
            this IBindingsBuilder <T> bindingsBuilder,
            string templateName,
            Expression <Func <T, F> > expression,
            string afterAdd            = null,
            string beforeRemove        = null,
            string afterRender         = null,
            object templateOptions     = null,
            string prefix              = null,
            bool applyClientValidation = true,
            bool fastNoJavaScript      = false,
            string afterAllRender      = null,
            string templateEngine      = null)
            where T : class
        {
            if (expression == null)
            {
                throw (new ArgumentNullException("expression"));
            }
            if (string.IsNullOrWhiteSpace(templateName))
            {
                throw (new ArgumentNullException("templateName"));
            }
            string format       = null;
            string actualPrefix = BasicHtmlHelper.AddField(
                bindingsBuilder.ModelPrefix,
                ExpressionHelper.GetExpressionText(expression));

            if (prefix == null)
            {
                prefix = actualPrefix;
            }
            StringBuilder sb = new StringBuilder();

            if (templateName[0] != '@')
            {
                sb.Append("template: { name: &quot;");
                sb.Append(templateName);
                if (typeof(IEnumerable).IsAssignableFrom(typeof(F)))
                {
                    sb.Append("&quot;, foreach: ");
                }
                else
                {
                    sb.Append("&quot;, data: ");
                }
            }
            else
            {
                templateName = templateName.Substring(1);
                sb.Append("template: { name: ");
                sb.Append(templateName);
                if (typeof(IEnumerable).IsAssignableFrom(typeof(F)))
                {
                    sb.Append(", foreach: ");
                }
                else
                {
                    sb.Append(", data: ");
                }
            }
            sb.Append(bindingsBuilder.GetFullBindingName(expression));

            if (afterRender != null)
            {
                sb.Append(", afterRender: ");
                sb.Append(afterRender);
            }
            if (afterAdd != null)
            {
                sb.Append(", afterAdd: ");
                sb.Append(afterAdd);
            }
            if (beforeRemove != null)
            {
                sb.Append(", beforeRemove: ");
                sb.Append(beforeRemove);
            }
            if (afterAllRender != null)
            {
                sb.Append(", afterAllRender: ");
                sb.Append(afterAllRender);
            }
            if (templateEngine != null)
            {
                sb.Append(", templateEngine: ko.");
                sb.Append(templateEngine);
                sb.Append(".instance");
            }
            var additionalOptions = new
            {
                ModelPrefix    = "&quot;" + prefix + "&quot;",
                ModelId        = "&quot;" + BasicHtmlHelper.IdFromName(prefix) + "&quot;",
                ItemPrefix     = "&quot;&quot;",
                templateSymbol = "&quot;" + ClientTemplateHelper.templateSymbol + "0&quot;"
            };

            sb.Append(", templateOptions: {");
            if (templateOptions != null)
            {
                sb.Append(BasicHtmlHelper.TranslateAnonymous(templateOptions));
                sb.Append(", ");
            }
            sb.Append(BasicHtmlHelper.TranslateAnonymous(additionalOptions));

            sb.Append(" }");
            sb.Append(", processingOptions: {");
            if (bindingsBuilder.ValidationType == "UnobtrusiveClient")
            {
                sb.Append("unobtrusiveClient: true");
                if (bindingsBuilder.GetHelper().ViewData["_TemplateLevel_"] == null)
                {
                    bindingsBuilder.AddServerErrors(actualPrefix);
                }
            }
            else
            {
                sb.Append("unobtrusiveClient: false");
            }
            sb.Append(fastNoJavaScript ? ", fastNoJavaScript: true" : ", fastNoJavaScript: false");
            sb.Append(applyClientValidation ? ", applyClientValidation: true" : ", applyClientValidation: false");
            sb.Append(" }");
            sb.Append(" }");
            format = sb.ToString();


            bindingsBuilder.Add(
                format
                );
            return(bindingsBuilder);
        }
Example #27
0
        public MvcHtmlString DateCalendar(CalendarOptions calendarOptions = null, bool inLine = true, IDictionary <string, object> containerHtmlAttributes = null)
        {
            if (this.dateRendered)
            {
                return(MvcHtmlString.Create(string.Empty));
            }
            if (!this.dateInCalendar)
            {
                throw new ArgumentException(ControlsResources.DateTimeInput_Calendar);
            }

            dateRendered = true;
            string newPrefix = BasicHtmlHelper.AddField(prefix, "$");



            StringBuilder sb = new StringBuilder();

            sb.Append(htmlHelper.Hidden(
                          BasicHtmlHelper.AddField(newPrefix, "Year"), Year).ToString());
            sb.Append(htmlHelper.Hidden(
                          BasicHtmlHelper.AddField(newPrefix, "Month"), Month).ToString());
            sb.Append(htmlHelper.Hidden(
                          BasicHtmlHelper.AddField(newPrefix, "Day"), Day).ToString());
            if (calendarOptions == null)
            {
                calendarOptions = new CalendarOptions();
            }
            string clientId = BasicHtmlHelper.IdFromName(BasicHtmlHelper.AddField(totalPrefix, "$"));

            if (string.IsNullOrWhiteSpace(calendarOptions.DateFormat))
            {
                calendarOptions.DateFormat = clientFormat;
            }
            clientFormat = calendarOptions.DateFormat;
            switch (clientFormat)
            {
            case "d": calendarOptions.DateFormat = System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat.ShortDatePattern;
                break;

            case "f": calendarOptions.DateFormat = System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat.LongDatePattern;
                break;

            case "F": calendarOptions.DateFormat = System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat.LongDatePattern;
                break;

            case "D": calendarOptions.DateFormat = System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat.LongDatePattern;
                break;

            case "M": calendarOptions.DateFormat = System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat.LongDatePattern;
                break;

            case "Y": calendarOptions.DateFormat = System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat.LongDatePattern;
                break;

            case "S": calendarOptions.DateFormat = "yyyy-MM-dd";
                break;

            case "t": calendarOptions.DateFormat = null;
                break;

            case "T": calendarOptions.DateFormat = null;
                break;

            default:
                calendarOptions.DateFormat = null;
                break;
            }
            if (calendarOptions.DateFormat != null)
            {
                calendarOptions.DateFormat = calendarOptions.DateFormat
                                             .Replace("yy", "y")
                                             .Replace("dddd", "DD")
                                             .Replace("ddd", "D")
                                             .Replace("M", "m")
                                             .Replace("mmmm", "MM")
                                             .Replace("mmm", "M");
            }
            //AddFunctions(ref containerHtmlAttributes, true);
            if (inLine)
            {
                sb.Append(string.Format(calendarSchema,
                                        clientId,
                                        calendarOptions.Render(clientId, inLine), BasicHtmlHelper.GetAttributesString(containerHtmlAttributes)));
            }
            else
            {
                sb.Append(string.Format(calendarSchemaOffLine,
                                        clientId,
                                        calendarOptions.Render(clientId, inLine), BasicHtmlHelper.GetAttributesString(containerHtmlAttributes)));
            }
            sb.Append(RenderBasicScripts(null));
            return(MvcHtmlString.Create(sb.ToString()));
        }
Example #28
0
        private static int TreeViewRec <VM, T> (
            StringBuilder sb,
            StringBuilder sbInit,
            bool editMode,
            HtmlHelper <VM> htmlHelper,
            RenderInfo <IEnumerable <T> > renderInfo,
            Func <int, string> collectionName,
            ExternalContainerType itemContainer,
            string rootClass,
            object[] itemTemplates,
            Func <object, int, int> itemTemplateSelector,
            Func <int, string> itemClassSelector,
            Func <object, int, TreeViewItemStatus> itemStatus,
            float opacity,
            bool canMove,
            int level,
            int totalCount,
            string fatherName,
            string root_id)
        {
            string basicId = BasicHtmlHelper.IdFromName(fatherName);



            sbInit.Append(renderInfo.PartialRendering);

            IDictionary <string, object> htmlAttributesContainer = new Dictionary <string, object>();

            string externalOpenTag  = null;
            string externalCloseTag = null;
            string handleClass      = basicId + "_handle";

            htmlAttributesContainer["id"] = basicId + "_ItemsContainer";
            if (level == 0)
            {
                htmlAttributesContainer["class"] = rootClass + "  mvcct-items-container";
                rootClass = null;
            }
            else
            {
                if (rootClass != null)
                {
                    htmlAttributesContainer["class"] = rootClass + "_  mvcct-items-container";
                }
            }
            BasicHtmlHelper.GetContainerTags(ExternalContainerType.ul, htmlAttributesContainer, out externalOpenTag, out externalCloseTag);
            sb.Append(externalOpenTag);

            IEnumerable list = renderInfo.Model as IEnumerable;

            if (list == null)
            {
                list = new List <T>();
            }

            string javasctiptOpacity = string.Empty;
            int    sonIndex          = -1;;

            foreach (object o in list)
            {
                if (o == null)
                {
                    continue;
                }
                totalCount++;
                sonIndex++;
                int    templateIndex   = itemTemplateSelector(o, level);
                object initialTemplate = itemTemplates[templateIndex];
                string initCollection  = collectionName(templateIndex);


                TreeViewItemStatus status = itemStatus(o, level);
                if (initCollection == null)
                {
                    status = TreeViewItemStatus.Hide;
                }
                ITreeViewNodeContainer wrapper  = null;
                IUpdateModel           uWrapper = null;
                bool closed = isClosed(status, o, htmlHelper);
                Type type   = TemplateInvoker <string> .ExtractModelType(initialTemplate);

                if (editMode)
                {
                    wrapper =
                        typeof(TreeViewUpdater <string>).GetGenericTypeDefinition()
                        .MakeGenericType(new Type[] { type })
                        .GetConstructor(new Type[0])
                        .Invoke(new object[0]) as ITreeViewNodeContainer;
                    uWrapper = wrapper as IUpdateModel;
                    uWrapper.ImportFromModel(o, null, null, new object[] { closed });
                }
                else
                {
                    wrapper  = new TreeViewUpdater <T>(false);
                    uWrapper = wrapper as IUpdateModel;
                }



                string prefix        = renderInfo.Prefix;
                string partialPrefix = renderInfo.PartialPrefix;
                if (editMode)
                {
                    sbInit.Append(
                        BasicHtmlHelper.RenderUpdateInfoI(htmlHelper, uWrapper, ref partialPrefix, new string[0]));
                }
                else
                {
                    BasicHtmlHelper.RenderUpdateInfoI(htmlHelper, uWrapper, ref partialPrefix, new string[0], noOutput: true);
                }
                prefix = htmlHelper.ViewData.TemplateInfo.GetFullHtmlFieldName(partialPrefix);
                if (level == 0)
                {
                    wrapper.FatherOriginalId = null;
                }
                else
                {
                    wrapper.FatherOriginalId = fatherName;
                }
                wrapper.OriginalId        = prefix;
                wrapper.PositionAsSon     = sonIndex;
                wrapper.SonNumber         = 0;
                wrapper.SonCollectionName = null;
                string itemOpenTag  = null;
                string itemCloseTag = null;

                string innerItemOpenTag  = null;
                string innerItemCloseTag = null;

                htmlAttributesContainer["id"]    = BasicHtmlHelper.IdFromName(BasicHtmlHelper.AddField(prefix, "Container"));
                htmlAttributesContainer["class"] = closed ? "closed" : "open";
                BasicHtmlHelper.GetContainerTags(ExternalContainerType.li, htmlAttributesContainer, out itemOpenTag, out itemCloseTag);

                htmlAttributesContainer["id"]    = BasicHtmlHelper.IdFromName(BasicHtmlHelper.AddField(prefix, "$.Item_SubContainer"));
                htmlAttributesContainer["class"] = handleClass;
                BasicHtmlHelper.GetContainerTags(itemContainer, htmlAttributesContainer, out innerItemOpenTag, out innerItemCloseTag);


                bool         hasCollection = true;
                string       name          = initCollection;
                PropertyInfo property      = null;
                if (name == null)
                {
                    hasCollection = false;
                }
                else
                {
                    property      = o.GetType().GetProperty(name);
                    hasCollection = typeof(IEnumerable).IsAssignableFrom(property.PropertyType);
                }
                sb.Append(itemOpenTag);

                if (canMove && hasCollection)
                {
                    sb.Append(string.Format("<input  type='checkbox' class ='level-select_{0} level-select' />", root_id));
                }
                sb.Append(innerItemOpenTag);
                sb.Append(
                    (typeof(TemplateInvoker <string>)
                     .GetGenericTypeDefinition()
                     .MakeGenericType(new Type[] { type })
                     .GetConstructor(new Type[] { typeof(object) })
                     .Invoke(new object[] { initialTemplate }) as ITemplateInvoker)
                    .Invoke(htmlHelper, o, BasicHtmlHelper.AddField(prefix, "$.Item")));
                sb.Append(innerItemCloseTag);

                if (hasCollection)
                {
                    string currItemClass = itemClassSelector == null ?
                                           null :
                                           itemClassSelector(templateIndex);
                    if (currItemClass != null)
                    {
                        currItemClass = currItemClass.Trim() + "_" + BasicHtmlHelper.IdFromName(renderInfo.Prefix);
                    }
                    ICollection innerItem   = property.GetValue(o, new object[0]) as ICollection;
                    Type        listType    = property.PropertyType.GetGenericArguments()[0];
                    Type        allListType = typeof(IEnumerable <string>).GetGenericTypeDefinition().MakeGenericType(listType);
                    if (innerItem == null)
                    {
                        innerItem = allListType.GetConstructor(new Type[0]).Invoke(new object[0]) as ICollection;
                    }
                    wrapper.SonNumber         = innerItem.Count;
                    wrapper.SonCollectionName = initCollection;
                    if (editMode)
                    {
                        RenderWrapper <VM>(htmlHelper, partialPrefix, wrapper, sbInit);
                    }

                    totalCount = (int)typeof(TreeViewHelpers).GetMethod("TreeViewRec", BindingFlags.Static | BindingFlags.NonPublic).
                                 MakeGenericMethod(new Type[] { typeof(VM), listType })
                                 .Invoke(null, new object[]
                                         { sb,
                                           sbInit,
                                           editMode,
                                           htmlHelper,
                                           typeof(RenderInfo <string>).GetGenericTypeDefinition().MakeGenericType(allListType)
                                           .GetConstructor(new Type[] { typeof(string), typeof(string), typeof(string), allListType })
                                           .Invoke
                                               (new object[] {
                            renderInfo.Prefix,
                            renderInfo.PartialPrefix,
                            string.Empty,
                            innerItem
                        }),
                                           collectionName,
                                           itemContainer,
                                           currItemClass,
                                           itemTemplates,
                                           itemTemplateSelector,
                                           itemClassSelector,
                                           itemStatus,
                                           opacity,
                                           canMove,
                                           level + 1,
                                           totalCount,
                                           prefix,
                                           root_id });
                }
                else
                {
                    if (editMode)
                    {
                        RenderWrapper <VM>(htmlHelper, partialPrefix, wrapper, sbInit);
                    }
                }
                sb.Append(itemCloseTag);
            }


            if (canMove)
            {
                if (opacity > 1f)
                {
                    opacity = 1f;
                }
                else if (opacity < 0.01f)
                {
                    opacity = 0.01f;
                }

                if (opacity < 1f)
                {
                    javasctiptOpacity = string.Format(" opacity: {0}, ", opacity.ToString(CultureInfo.InvariantCulture));
                }
                string javascriptRootClass = string.Empty;
                if (rootClass != null)
                {
                    javascriptRootClass = string.Format(" connectWith: '.{0}', ", rootClass);
                }
                if (level > 0)
                {
                    sbInit.Append(string.Format(startScriptFormat,
                                                basicId,
                                                javasctiptOpacity,
                                                javascriptRootClass,
                                                root_id));
                }
            }
            else
            {
                if (level > 0)
                {
                    sbInit.Append(string.Format(startScriptNoMoveFormat,
                                                basicId,
                                                root_id));
                }
            }
            sb.Append(externalCloseTag);


            return(totalCount);
        }
Example #29
0
        public static MvcHtmlString TreeViewFor <VM, TItem>(
            this HtmlHelper <VM> htmlHelper,
            RenderInfo <IEnumerable <TItem> > renderInfo,
            Func <int, string> collectionName,
            ExternalContainerType itemContainer = ExternalContainerType.span,
            string rootClassDisplay             = null,
            object[] displayTemplates           = null,
            Func <object, int, int> itemTemplateSelectorDisplay = null,
            string rootClassEdit   = null,
            object[] editTemplates = null,
            Func <object, int, int> itemTemplateSelectorEdit = null,
            TreeViewMode mode = TreeViewMode.InitializeDisplay,
            Func <int, string> itemClassSelector = null,
            Func <object, int, TreeViewItemStatus> itemStatus = null,
            TreeViewOptions treeViewOptions = null)
        {
            if (renderInfo == null)
            {
                throw(new ArgumentNullException("renderInfo"));
            }
            if (collectionName == null)
            {
                throw(new ArgumentNullException("collectionName"));
            }
            if ((displayTemplates == null || itemTemplateSelectorDisplay == null || displayTemplates.Length == 0) &&
                (editTemplates == null || itemTemplateSelectorEdit == null || editTemplates.Length == 0))
            {
                throw (new ArgumentNullException("displayTemplates/itemTemplateSelectorDisplay or editTemplates/itemTemplateSelectorEdit"));
            }
            if (itemStatus == null)
            {
                itemStatus = (mbox, i) => TreeViewItemStatus.initializeShow;
            }
            if (treeViewOptions == null)
            {
                treeViewOptions = new TreeViewOptions();
            }

            if (MvcEnvironment.Validation(htmlHelper) == ValidationType.StandardClient)
            {
                treeViewOptions.CanAdd = false;
            }

            StringBuilder sb = new StringBuilder();

            sb.Append(renderInfo.PartialRendering);

            RenderInfo <IEnumerable <TItem> > renderInfoO = new RenderInfo <IEnumerable <TItem> >();

            renderInfoO.Model            = renderInfo.Model;
            renderInfoO.PartialPrefix    = renderInfo.PartialPrefix;
            renderInfoO.Prefix           = renderInfo.Prefix;
            renderInfoO.PartialRendering = renderInfo.PartialRendering;



            if (editTemplates == null || editTemplates.Length == 0)
            {
                TreeViewTop <VM, TItem>(
                    sb, false, htmlHelper, renderInfoO, collectionName, itemContainer,
                    rootClassDisplay, displayTemplates, itemTemplateSelectorDisplay,
                    itemClassSelector, itemStatus, treeViewOptions.Opacity, false, false, treeViewOptions);
            }
            else if (displayTemplates == null || displayTemplates.Length == 0)
            {
                TreeViewTop <VM, TItem>(
                    sb, true, htmlHelper, renderInfoO, collectionName, itemContainer,
                    rootClassEdit, editTemplates, itemTemplateSelectorEdit,
                    itemClassSelector, itemStatus, treeViewOptions.Opacity, treeViewOptions.CanMove, treeViewOptions.CanAdd, treeViewOptions);
            }
            else
            {
                bool isEdit = mode == TreeViewMode.Edit || mode == TreeViewMode.InitializeEdit;
                if (mode == TreeViewMode.InitializeEdit || mode == TreeViewMode.InitializeDisplay)
                {
                    IDictionary vars = htmlHelper.ViewContext.RequestContext.HttpContext.Items;
                    if (vars.Contains(renderInfo.Prefix))
                    {
                        isEdit = (bool)(vars[renderInfo.Prefix]);
                    }
                }
                string toggleScript = null;
                if (isEdit)
                {
                    toggleScript = string.Format(completeTreeScriptEdit,
                                                 BasicHtmlHelper.IdFromName(renderInfo.Prefix));
                }
                else
                {
                    toggleScript = string.Format(completeTreeScriptDisplay,
                                                 BasicHtmlHelper.IdFromName(renderInfo.Prefix));
                }

                RenderInfo <TwoWayChoice <IEnumerable <TItem> > > toRender = htmlHelper.InvokeTransform(renderInfo, new TwoWayChoice <IEnumerable <TItem> >());
                toRender.Model.IsChoice2 = isEdit;
                sb.Append(toRender.PartialRendering);
                sb.Append(htmlHelper.Hidden(BasicHtmlHelper.AddField(toRender.PartialPrefix, "IsChoice2"), toRender.Model.IsChoice2));
                renderInfoO.Model            = toRender.Model.Choice1;
                renderInfoO.PartialPrefix    = BasicHtmlHelper.AddField(toRender.PartialPrefix, "Choice1");
                renderInfoO.Prefix           = BasicHtmlHelper.AddField(toRender.Prefix, "Choice1");
                renderInfoO.PartialRendering = string.Empty;

                TreeViewTop <VM, TItem>(
                    sb, false, htmlHelper, renderInfoO, collectionName, itemContainer,
                    rootClassDisplay, displayTemplates, itemTemplateSelectorDisplay,
                    itemClassSelector, itemStatus, treeViewOptions.Opacity, false, false, treeViewOptions);


                renderInfoO.Model         = toRender.Model.Choice2;
                renderInfoO.PartialPrefix = BasicHtmlHelper.AddField(toRender.PartialPrefix, "Choice2");
                renderInfoO.Prefix        = BasicHtmlHelper.AddField(toRender.Prefix, "Choice2");


                TreeViewTop <VM, TItem>(
                    sb, true, htmlHelper, renderInfoO, collectionName, itemContainer,
                    rootClassEdit, editTemplates, itemTemplateSelectorEdit,
                    itemClassSelector, itemStatus, treeViewOptions.Opacity, treeViewOptions.CanMove, treeViewOptions.CanAdd, treeViewOptions);

                sb.Append(toggleScript);
            }

            return(MvcHtmlString.Create(sb.ToString()));
        }
Example #30
0
        protected void ComputeClientRangeScript()
        {
            if (constraints == null || constraints.Length == 0)
            {
                return;
            }
            StringBuilder sbMin        = new StringBuilder();
            StringBuilder sbMax        = new StringBuilder();
            StringBuilder sUp          = new StringBuilder();
            string        prefix       = this.totalPrefix;
            string        fatherPrefix = BasicHtmlHelper.PreviousPrefix(prefix);

            currMin = min;
            currMax = max;
            string myClientId = BasicHtmlHelper.IdFromName(BasicHtmlHelper.AddField(prefix, "$"));

            foreach (DateRangeAttribute c in constraints)
            {
                c.RetriveDynamicDelays(htmlHelper.ViewData.Model, fatherPrefix);
                if (!string.IsNullOrWhiteSpace(c.DynamicMaximum) && c.RangeAction == RangeAction.Verify)
                {
                    bool             isMilestone        = false;
                    string           path               = (fatherPrefix.Length != 0 ? fatherPrefix + "." + c.DynamicMaximum : c.DynamicMaximum);
                    string           clientId           = BasicHtmlHelper.IdFromName(BasicHtmlHelper.AddField(path, "$"));
                    PropertyAccessor dynamicMaximumProp = new PropertyAccessor(htmlHelper.ViewData.Model,
                                                                               path, false);
                    TimeSpan delay = new TimeSpan(0L);
                    if (c.MaximumDelay != null && c.MaximumDelay.HasValue)
                    {
                        delay = c.MaximumDelay.Value;
                    }
                    if (dynamicMaximumProp != null && dynamicMaximumProp.Value != null)
                    {
                        MileStoneAttribute[] ma = dynamicMaximumProp[typeof(MileStoneAttribute)] as MileStoneAttribute[];
                        if (ma != null && ma.Length > 0)
                        {
                            isMilestone = true;
                            if (dynamicMaximumProp.Property.PropertyType == typeof(DateTime))
                            {
                                if (max == null || !max.HasValue || (((DateTime)dynamicMaximumProp.Value).Add(delay) < max))
                                {
                                    max = ((DateTime)dynamicMaximumProp.Value).Add(delay);
                                }
                            }
                            else if (dynamicMaximumProp.Property.PropertyType == typeof(Nullable <DateTime>))
                            {
                                Nullable <DateTime> pmax = dynamicMaximumProp.Value as Nullable <DateTime>;
                                if (pmax.HasValue)
                                {
                                    pmax = pmax.Value.Add(delay);
                                }
                                if (pmax.HasValue && (max == null || !max.HasValue || pmax < currMax))
                                {
                                    currMax = pmax;
                                }
                            }
                        }
                        if (dynamicMaximumProp.Property.PropertyType == typeof(DateTime))
                        {
                            if (currMax == null || !currMax.HasValue || (((DateTime)dynamicMaximumProp.Value).Add(delay) < currMax))
                            {
                                currMax = ((DateTime)dynamicMaximumProp.Value).Add(delay);
                            }
                        }
                        else if (dynamicMaximumProp.Property.PropertyType == typeof(Nullable <DateTime>))
                        {
                            Nullable <DateTime> pmax = dynamicMaximumProp.Value as Nullable <DateTime>;
                            if (pmax.HasValue)
                            {
                                pmax = pmax.Value.Add(delay);
                            }
                            if (pmax.HasValue && (currMax == null || !currMax.HasValue || pmax < currMax))
                            {
                                currMax = pmax;
                            }
                        }
                        else
                        {
                            throw (new InvalidDynamicRangeException(AnnotationsRsources.InvalidUpperDynamicRange));
                        }
                    }
                    if (!isMilestone)
                    {
                        string varId =
                            BasicHtmlHelper.IdFromName(
                                (fatherPrefix.Length != 0 ? fatherPrefix + "." + c.DynamicMaximum : c.DynamicMaximum) + ".$.Curr");

                        sbMax.Append(string.Format("if ({0} != null){{ cmax = new Date({0}.getTime()+{1});  if (max == null || cmax < max) max = cmax;}}",
                                                   varId, delay.Ticks / 10000));
                        sUp.Append(string.Format(updateSchema, clientId, myClientId));
                    }
                }
                if (!string.IsNullOrWhiteSpace(c.DynamicMinimum) && c.RangeAction == RangeAction.Verify)
                {
                    bool             isMilestone        = false;
                    string           path               = (fatherPrefix.Length != 0 ? fatherPrefix + "." + c.DynamicMinimum : c.DynamicMinimum);
                    string           clientId           = BasicHtmlHelper.IdFromName(BasicHtmlHelper.AddField(path, "$"));
                    PropertyAccessor dynamicMinimumProp = new PropertyAccessor(htmlHelper.ViewData.Model,
                                                                               path, false);
                    TimeSpan delay = new TimeSpan(0L);
                    if (c.MinimumDelay != null && c.MinimumDelay.HasValue)
                    {
                        delay = c.MinimumDelay.Value;
                    }
                    if (dynamicMinimumProp != null && dynamicMinimumProp.Value != null)
                    {
                        MileStoneAttribute[] ma = dynamicMinimumProp[typeof(MileStoneAttribute)] as MileStoneAttribute[];
                        if (ma != null && ma.Length > 0)
                        {
                            isMilestone = true;
                            if (dynamicMinimumProp.Property.PropertyType == typeof(DateTime))
                            {
                                if (min == null || !min.HasValue || (((DateTime)dynamicMinimumProp.Value).Add(delay) > min))
                                {
                                    min = ((DateTime)dynamicMinimumProp.Value).Add(delay);
                                }
                            }
                            else if (dynamicMinimumProp.Property.PropertyType == typeof(Nullable <DateTime>))
                            {
                                Nullable <DateTime> pmin = dynamicMinimumProp.Value as Nullable <DateTime>;
                                if (pmin.HasValue)
                                {
                                    pmin = pmin.Value.Add(delay);
                                }
                                if (pmin.HasValue && (min == null || !min.HasValue || pmin > min))
                                {
                                    min = pmin;
                                }
                            }
                        }
                        if (dynamicMinimumProp.Property.PropertyType == typeof(DateTime))
                        {
                            if (currMin == null || !currMin.HasValue || (((DateTime)dynamicMinimumProp.Value).Add(delay) > currMin))
                            {
                                currMin = ((DateTime)dynamicMinimumProp.Value).Add(delay);
                            }
                        }
                        else if (dynamicMinimumProp.Property.PropertyType == typeof(Nullable <DateTime>))
                        {
                            Nullable <DateTime> pmin = dynamicMinimumProp.Value as Nullable <DateTime>;
                            if (pmin.HasValue)
                            {
                                pmin = pmin.Value.Add(delay);
                            }
                            if (pmin.HasValue && (currMin == null || !currMin.HasValue || pmin > currMin))
                            {
                                currMin = pmin;
                            }
                        }
                        else
                        {
                            throw (new InvalidDynamicRangeException(AnnotationsRsources.InvalidUpperDynamicRange));
                        }
                    }
                    if (!isMilestone)
                    {
                        string varId =
                            BasicHtmlHelper.IdFromName(
                                (fatherPrefix.Length != 0 ? fatherPrefix + "." + c.DynamicMinimum : c.DynamicMinimum) + ".$.Curr");

                        sbMin.Append(string.Format("if ({0} != null){{ cmin = new Date({0}.getTime()+{1});  if (min == null || cmin > min) min = cmin;}}",
                                                   varId, delay.Ticks / 10000));

                        sUp.Append(string.Format(updateSchema, clientId, myClientId));
                    }
                }
            }
            if (currMin != null && currMin.HasValue && curr != null && curr.HasValue && curr < currMin)
            {
                curr = currMin;
            }
            if (currMax != null && currMax.HasValue && curr != null && curr.HasValue && curr > currMax)
            {
                curr = currMax;
            }
            clientMinScript            = sbMin.ToString();
            clientMaxScript            = sbMax.ToString();
            clientRefreshRegistrations = sUp.ToString();
        }