コード例 #1
0
        public MvcHtmlString SelectedItems(IDictionary <string, object> htmlAttributes = null)
        {
            List <ExtendedSelectListItem> selected = new List <ExtendedSelectListItem>();

            foreach (TValue val in Value)
            {
                if (allItemsDictionary.ContainsKey(val.ToString()))
                {
                    selected.Add(allItemsDictionary[val.ToString()]);
                }
            }
            if (htmlAttributes == null)
            {
                htmlAttributes = new Dictionary <string, object>();
            }
            htmlAttributes["data-elementispart"] = "true";
            return(MvcHtmlString.Create
                   (
                       RenderPackedList() +
                       CurrHtmlHelper.DropDownbase <TModel, TChoiceItem, TDisplay, TValue> (
                           BasicHtmlHelper.AddField(Prefix, "$.PackedValue") + DualSelect_SelectSelected,
                           new List <TValue>() as IEnumerable <TValue>,
                           selected,
                           htmlAttributes,
                           true,
                           false).ToString()
                   ));
        }
コード例 #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();
         }
     }
 }
コード例 #3
0
ファイル: DataGridItem.cs プロジェクト: nomada2/MvcKompAppGit
        internal string GetChangedItem(string prefix,
                                       HtmlHelper <TModel> htmlHelper,
                                       object displayTemplate,
                                       ItemContainerType itemContainerType,
                                       IDictionary <string, object> htmlattributes,
                                       int index,
                                       bool normal,
                                       Func <TItem, int, string> getDynamicContainer = null
                                       )
        {
            string openTag;
            string closureTag;

            GetItemContainerTags(
                itemContainerType,
                index,
                getDynamicContainer,
                htmlattributes,
                BasicHtmlHelper.AddField(prefix, "$.Item.Value.ChangedExternally"),
                !normal,
                out openTag,
                out closureTag);
            return(string.Format("{1} {0} {2}",
                                 (Item.Changed ?
                                  GetOldContentRendering(prefix, htmlHelper, displayTemplate) :
                                  GetContentRendering(prefix, htmlHelper, displayTemplate)),
                                 openTag,
                                 closureTag));
        }
コード例 #4
0
        public MvcHtmlString AvailableItems(IDictionary <string, object> htmlAttributes = null)
        {
            List <ExtendedSelectListItem> NotSelected = new List <ExtendedSelectListItem>();

            foreach (ExtendedSelectListItem sel in allItems)
            {
                if (!valuesSet.Contains(sel.Value))
                {
                    NotSelected.Add(sel);
                }
            }
            if (htmlAttributes == null)
            {
                htmlAttributes = new Dictionary <string, object>();
            }
            htmlAttributes["data-elementispart"] = "true";
            return(MvcHtmlString.Create
                   (

                       CurrHtmlHelper.DropDownbase <TModel, TChoiceItem, TDisplay, TValue>(
                           BasicHtmlHelper.AddField(Prefix, "$.PackedValue") + DualSelect_SelectAvial,
                           new List <TValue>() as IEnumerable <TValue>,
                           NotSelected,
                           htmlAttributes,
                           true,
                           false).ToString()
                   ));
        }
コード例 #5
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;
        }
コード例 #6
0
        protected string RenderPackedList()
        {
            PackedList <IEnumerable <TValue>, TValue> displayModel = new PackedList <IEnumerable <TValue>, TValue>();

            displayModel.ImportFromModel(Value, new object[] { DualSelect_Separator });

            StringBuilder sb = new StringBuilder();

            sb.Append(BasicHtmlHelper.RenderDisplayInfo(CurrHtmlHelper,
                                                        typeof(PackedList <IEnumerable <TValue>, TValue>),
                                                        Prefix));
            sb.AppendFormat("<span {2} style='display:none' id='{1}' is-item-control='true' pname='{0}' data-element-type = 'DualSelect' ></span>", _fullprefix, BasicHtmlHelper.IdFromName(_fullprefix), BasicHtmlHelper.GetAttributesString(AttributeExtensions));
            sb.Append(
                CurrHtmlHelper.Hidden(BasicHtmlHelper.AddField(Prefix, "$.Separator"),
                                      DualSelect_Separator, new RouteValueDictionary {
                { "data-elementispart", "true" }
            })).ToString();

            sb.Append(CurrHtmlHelper.Hidden(
                          BasicHtmlHelper.AddField(Prefix, "$.PackedValue"),
                          displayModel.PackedValue, new RouteValueDictionary {
                { "data-elementispart", "true" }
            }));
            return(sb.ToString());
        }
コード例 #7
0
 public string GetFullName <F>(Expression <Func <M, F> > expression)
 {
     if (expression == null)
     {
         throw (new ArgumentNullException("expression"));
     }
     return(BasicHtmlHelper.AddField(modelPrefix, ExpressionHelper.GetExpressionText(expression)));
 }
コード例 #8
0
 public MvcHtmlString SelectedItemsFilter(IDictionary <string, object> htmlAttributes = null)
 {
     return(MvcHtmlString.Create(
                CurrHtmlHelper.TextBox(
                    BasicHtmlHelper.AddField(Prefix, "$.PackedValue") + DualSelect_SelectedFilter,
                    null,
                    htmlAttributes).ToString() +
                string.Format(script, controlId, "true")
                ));
 }
コード例 #9
0
        internal HtmlHelper <T> GetHelper(HtmlHelper <M> htmlHelper, string partialPrefix, string prefix)
        {
            htmlHelper.ViewContext.Writer.Write(
                BasicHtmlHelper.RenderDisplayInfo(htmlHelper, this.GetType(), partialPrefix));
            ViewDataDictionary <T> dataDictionary =
                new ViewDataDictionary <T>(FilterDescription);

            dataDictionary.TemplateInfo.HtmlFieldPrefix = BasicHtmlHelper.AddField(prefix, "$.FilterDescription");
            BasicHtmlHelper.CopyRelevantErrors(dataDictionary.ModelState, htmlHelper.ViewData.ModelState, dataDictionary.TemplateInfo.HtmlFieldPrefix);
            return(new TemplateInvoker <T>().BuildHelper(htmlHelper, dataDictionary));
        }
コード例 #10
0
        public HtmlHelper <S> To <S>()
            where S : class
        {
            RenderInfo <IDisplayModel> r = htmlHelper.InvokeTransformExt(renderInfo, createHandler <S>(renderInfo.Model), duplicate: true);

            htmlHelper.ViewContext.Writer.WriteLine(r.GetPartialrendering());
            ViewDataDictionary <S> dataDictionary = new ViewDataDictionary <S>(renderInfo.Model as S);

            dataDictionary.TemplateInfo.HtmlFieldPrefix = BasicHtmlHelper.AddField(r.Prefix, "Item");
            BasicHtmlHelper.CopyRelevantErrors(dataDictionary.ModelState, htmlHelper.ViewData.ModelState, dataDictionary.TemplateInfo.HtmlFieldPrefix);
            return(new TemplateInvoker <S>().BuildHelper(htmlHelper, dataDictionary));
        }
コード例 #11
0
ファイル: DataGridItem.cs プロジェクト: nomada2/MvcKompAppGit
        protected string GetOldContentRendering(string prefix, HtmlHelper <TModel> htmlHelper, object template)
        {
            ViewDataDictionary <TItem> dataDictionary = new ViewDataDictionary <TItem>(Item.OldValue);

            if (htmlHelper.ViewData.ContainsKey("ThemeParams"))
            {
                dataDictionary["ThemeParams"] = htmlHelper.ViewData["ThemeParams"] as GridDescriptionBase;
            }
            dataDictionary.TemplateInfo.HtmlFieldPrefix = BasicHtmlHelper.AddField(prefix, "$.Item.Value");
            BasicHtmlHelper.CopyRelevantErrors(dataDictionary.ModelState, htmlHelper.ViewData.ModelState, dataDictionary.TemplateInfo.HtmlFieldPrefix);
            dataDictionary["status"] = status;
            return(new TemplateInvoker <TItem>(template).Invoke <TModel>(htmlHelper, dataDictionary));
        }
コード例 #12
0
        internal MvcHtmlString Render(HtmlHelper <M> htmlHelper, string partialPrefix, string prefix, object template)
        {
            StringBuilder sb = new StringBuilder();

            sb.Append(BasicHtmlHelper.RenderDisplayInfo(htmlHelper, this.GetType(), partialPrefix));
            ViewDataDictionary <T> dataDictionary =
                new ViewDataDictionary <T>(FilterDescription);

            dataDictionary.TemplateInfo.HtmlFieldPrefix = BasicHtmlHelper.AddField(prefix, "$.FilterDescription");
            BasicHtmlHelper.CopyRelevantErrors(dataDictionary.ModelState, htmlHelper.ViewData.ModelState, dataDictionary.TemplateInfo.HtmlFieldPrefix);
            sb.Append(new TemplateInvoker <T>(template).Invoke <M>(htmlHelper, dataDictionary));
            return(MvcHtmlString.Create(sb.ToString()));
        }
コード例 #13
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());
        }
コード例 #14
0
        public string GetFullBindingName(LambdaExpression expression)
        {
            if (expression == null)
            {
                throw (new ArgumentNullException("expression"));
            }
            string res = BasicHtmlHelper.AddField(bindingPrefix, ExpressionHelper.GetExpressionText(expression));

            if (string.IsNullOrWhiteSpace(res))
            {
                return("$data");
            }
            return(res);
        }
コード例 #15
0
        public MvcHtmlString Invoke <S>(object template)
            where S : class
        {
            if (template == null)
            {
                throw(new ArgumentNullException("template"));
            }
            RenderInfo <IDisplayModel> r = htmlHelper.InvokeTransformExt(renderInfo, createHandler <S>(renderInfo.Model), duplicate: true);
            ViewDataDictionary <S>     dataDictionary = new ViewDataDictionary <S>(renderInfo.Model as S);

            dataDictionary.TemplateInfo.HtmlFieldPrefix = BasicHtmlHelper.AddField(r.Prefix, "Item");
            BasicHtmlHelper.CopyRelevantErrors(dataDictionary.ModelState, htmlHelper.ViewData.ModelState, dataDictionary.TemplateInfo.HtmlFieldPrefix);
            return(MvcHtmlString.Create(r.GetPartialrendering() + (new TemplateInvoker <S>().Invoke(htmlHelper, dataDictionary))));
        }
コード例 #16
0
ファイル: DataGridItem.cs プロジェクト: nomada2/MvcKompAppGit
        internal string GetChangedAndOldValuesRendering(string prefix, HtmlHelper <TModel> htmlHelper)
        {
            StringBuilder sb = new StringBuilder();

            sb.Append(BasicHtmlHelper.SafeHidden(htmlHelper, BasicHtmlHelper.AddField(prefix, "$.Item.Changed"), this.Item.Changed).ToString());
            if (this.Item != null && this.Item.OldValue != null)
            {
                prefix = BasicHtmlHelper.AddField(prefix, "$.Item.OldValue");
                if (fieldsToStore != null)
                {
                    foreach (LambdaExpression l in fieldsToStore)
                    {
                        object val  = null;
                        string name = ExpressionHelper.GetExpressionText(l);
                        try
                        {
                            val = l.Compile().DynamicInvoke(this.Item.OldValue);
                        }
                        catch
                        {
                        }
                        if (val is IConvertible || val is Guid)
                        {
                            string res = BasicHtmlHelper.SafeHidden(htmlHelper,
                                                                    BasicHtmlHelper.AddField(prefix, name), val).ToString();
                            sb.Append(res);
                        }
                        else
                        {
                            MVCControlsToolkit.Controls.Bindings.ModelTranslatorLight model = new MVCControlsToolkit.Controls.Bindings.ModelTranslatorLight();
                            model.ImportFromModel(val);
                            sb.Append(BasicHtmlHelper.RenderDisplayInfo(htmlHelper, typeof(MVCControlsToolkit.Controls.Bindings.ModelTranslatorLight),
                                                                        BasicHtmlHelper.AddField(prefix, name)));
                            string res = BasicHtmlHelper.SafeHidden(htmlHelper,
                                                                    BasicHtmlHelper.AddField(prefix, name + ".$.JSonModel"), model.JSonModel).ToString();
                            sb.Append(res);
                        }
                    }
                }
                else
                {
                    Stack <object> recursionControl = new Stack <object>();
                    recursionControl.Push(this.Item.OldValue);
                    addObjectPropertiesTorender(prefix, htmlHelper, sb, propertiesToStore, this.Item.OldValue, recursionControl);
                    recursionControl.Pop();
                }
            }
            return(sb.ToString());
        }
コード例 #17
0
 private static void RenderWrapper <VM>(HtmlHelper <VM> htmlHelper, string partialPrefix, ITreeViewNodeContainer wrapper, StringBuilder sbInit)
 {
     sbInit.Append(htmlHelper.GenericInput(InputType.Hidden, BasicHtmlHelper.AddField(partialPrefix, "$.Closed"),
                                           wrapper.Closed).ToString());
     sbInit.Append(htmlHelper.GenericInput(InputType.Hidden, BasicHtmlHelper.AddField(partialPrefix, "$.FatherOriginalId"),
                                           wrapper.FatherOriginalId).ToString());
     sbInit.Append(htmlHelper.GenericInput(InputType.Hidden, BasicHtmlHelper.AddField(partialPrefix, "$.OriginalId"),
                                           wrapper.OriginalId).ToString());
     sbInit.Append(htmlHelper.GenericInput(InputType.Hidden, BasicHtmlHelper.AddField(partialPrefix, "$.PositionAsSon"),
                                           wrapper.PositionAsSon).ToString());
     sbInit.Append(htmlHelper.GenericInput(InputType.Hidden, BasicHtmlHelper.AddField(partialPrefix, "$.SonCollectionName"),
                                           wrapper.SonCollectionName).ToString());
     sbInit.Append(htmlHelper.GenericInput(InputType.Hidden, BasicHtmlHelper.AddField(partialPrefix, "$.SonNumber"),
                                           wrapper.SonNumber).ToString());
 }
コード例 #18
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);
            }
        }
コード例 #19
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()));
        }
コード例 #20
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());
        }
コード例 #21
0
        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()));
        }
コード例 #22
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)));
            }
        }/*
コード例 #23
0
        public static MvcHtmlString DetailFormSyncInfos <TItem, T>
            (this HtmlHelper <TItem> htmlHelper,
            Expression <Func <TItem, T> > expression,
            string formattedValue,
            bool htmlEncode = true,
            string urlValue = null)
        {
            if (expression == null)
            {
                throw (new ArgumentException("expression"));
            }
            string trueValue = string.Empty;
            string id        = BasicHtmlHelper.IdFromName(
                BasicHtmlHelper.AddField(
                    htmlHelper.ViewData.TemplateInfo.HtmlFieldPrefix,
                    ExpressionHelper.GetExpressionText(expression)));

            if (!typeof(IConvertible).IsAssignableFrom(typeof(T)))
            {
                T model = default(T);
                try{
                    model = expression.Compile().Invoke(htmlHelper.ViewData.Model);
                }
                catch {
                }
                trueValue = string.Format(
                    "var {0}_True = '{1}'; ",
                    id,
                    htmlHelper.Encode(BasicHtmlHelper.ClientEncode(model)));
            }
            string fUrlValue = string.Empty;

            if (urlValue != null)
            {
                fUrlValue = string.Format(
                    "var {0}_Url = '{1}'; ",
                    id,
                    htmlHelper.Encode(urlValue));
            }
            string fFormattevValue = string.Empty;
            string html            = string.Empty;

            if (formattedValue != null)
            {
                if (htmlEncode)
                {
                    fFormattevValue = string.Format(
                        "var {0}_Format = '{1}'; ",
                        id,
                        htmlHelper.Encode(formattedValue));
                }
                else
                {
                    html = string.Format(
                        @"<span id='{0}_Format' style='display:none'>
                        {1}
                        </span>
                        ",
                        id,
                        htmlHelper.Encode(formattedValue));
                    fFormattevValue = string.Format(
                        @"var {0}_Format = '<>'; ",
                        id);
                }
            }
            return(MvcHtmlString.Create(
                       string.Format(syncScript, trueValue, fUrlValue, fFormattevValue, html)));
        }
コード例 #24
0
ファイル: DataGridItem.cs プロジェクト: nomada2/MvcKompAppGit
 private void addObjectPropertiesTorender(string prefix,
                                          HtmlHelper <TModel> htmlHelper,
                                          StringBuilder sb,
                                          PropertyInfo[] propertiesToStore,
                                          object obj,
                                          Stack <object> recursionControl)
 {
     foreach (PropertyInfo pi in propertiesToStore)
     {
         if (pi.GetIndexParameters().GetLength(0) > 0)
         {
             continue;
         }
         object val = pi.GetValue(obj, new object[0]);
         if (val is IConvertible)
         {
             string res = BasicHtmlHelper.SafeHidden(htmlHelper,
                                                     BasicHtmlHelper.AddField(prefix, pi.Name), val).ToString();
             sb.Append(res);
         }
         else if (val is IEnumerable)
         {
             bool recursion = false;
             foreach (object ob in recursionControl)
             {
                 if (object.ReferenceEquals(val, ob))
                 {
                     recursion = true;
                 }
                 ;
             }
             if (recursion)
             {
                 continue;
             }
             recursionControl.Push(val);
             addIEnumerablePropertiesTorender(
                 BasicHtmlHelper.AddField(prefix, pi.Name),
                 htmlHelper,
                 sb,
                 val as IEnumerable,
                 recursionControl);
             recursionControl.Pop();
         }
         else if (val != null)
         {
             bool recursion = false;
             foreach (object ob in recursionControl)
             {
                 if (object.ReferenceEquals(val, ob))
                 {
                     recursion = true;
                 }
             }
             if (recursion)
             {
                 continue;
             }
             recursionControl.Push(val);
             addObjectPropertiesTorender(
                 BasicHtmlHelper.AddField(prefix, pi.Name),
                 htmlHelper,
                 sb,
                 BasicHtmlHelper.GetPropertiesForInput(val.GetType()), val, recursionControl);
             recursionControl.Pop();
         }
     }
 }
コード例 #25
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);
        }
コード例 #26
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();
        }
コード例 #27
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);
        }
コード例 #28
0
        public MvcHtmlString Time(bool dateHidden = false, IDictionary <string, object> htmlAttributes = null, CultureInfo culture = null)
        {
            if (timeRendered)
            {
                return(MvcHtmlString.Create(string.Empty));
            }
            timeRendered    = true;
            this.dateHidden = dateHidden;
            if (culture == null)
            {
                culture = CultureInfo.CurrentUICulture;
            }
            string newPrefix = BasicHtmlHelper.AddField(prefix, "$");

            if (htmlAttributes == null)
            {
                htmlAttributes = new Dictionary <string, object>();
            }
            htmlAttributes["data-elementispart"] = "true";
            DateTime?min = currMin;
            DateTime?max = currMax;

            StringBuilder sb = new StringBuilder();

            sb.Append(RenderBasicScripts(culture));
            htmlAttributes["maxlength"] = "2";
            BasicHtmlHelper.SetDefaultStyle(htmlAttributes, "text-align", "right");
            if (dateHidden)
            {
                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());
            }


            string separator = culture.DateTimeFormat.TimeSeparator;

            bool applyRestrictionsMin = min != null && min.HasValue &&
                                        min.Value.Year == curr.Value.Year && min.Value.Month == curr.Value.Month &&
                                        min.Value.Day == curr.Value.Day;

            bool applyRestrictionsMax = max != null && max.HasValue &&
                                        curr.Value.Year == max.Value.Year && curr.Value.Month == max.Value.Month &&
                                        curr.Value.Day == max.Value.Day;

            int minHour = 0;
            int maxHour = 23;

            if (applyRestrictionsMin)
            {
                if (min.Value.Hour > minHour)
                {
                    minHour = min.Value.Hour;
                }
            }
            else
            {
                applyRestrictionsMin = false;
            }
            if (applyRestrictionsMax)
            {
                if (max.Value.Hour < maxHour)
                {
                    maxHour = max.Value.Hour;
                }
            }
            else
            {
                applyRestrictionsMax = false;
            }

            List <SelectListItem> allHours = new List <SelectListItem>(1);

            for (int hour = Hours; hour <= Hours; hour++)
            {
                allHours.Add(new SelectListItem()
                {
                    Value    = hour.ToString(),
                    Text     = hour.ToString("00"),
                    Selected = Hours == hour
                });
            }
            //AddFunctions(ref htmlAttributes, false);
            sb.Append(htmlHelper.DropDownList(
                          BasicHtmlHelper.AddField(newPrefix, "Hours"),
                          allHours,
                          htmlAttributes).ToString());
            sb.Append(string.Format("<span class='{0}'>{1}</span>", htmlAttributes["style"].ToString(), separator));
            int minMinute = 0;
            int maxMinute = 59;

            if (applyRestrictionsMin)
            {
                if (min.Value.Minute > minMinute)
                {
                    minMinute = min.Value.Minute;
                }
            }
            else
            {
                applyRestrictionsMin = false;
            }

            if (applyRestrictionsMax)
            {
                if (max.Value.Minute < maxMinute)
                {
                    maxMinute = max.Value.Minute;
                }
            }
            else
            {
                applyRestrictionsMax = false;
            }

            List <SelectListItem> allMinutes = new List <SelectListItem>(1);

            for (int minute = Minutes; minute <= Minutes; minute++)
            {
                allMinutes.Add(new SelectListItem()
                {
                    Value    = minute.ToString(),
                    Text     = minute.ToString("00"),
                    Selected = Minutes == minute
                });
            }
            //AddFunctions(ref htmlAttributes, false);
            sb.Append(htmlHelper.DropDownList(
                          BasicHtmlHelper.AddField(newPrefix, "Minutes"),
                          allMinutes,
                          htmlAttributes).ToString());

            sb.Append(string.Format("<span class='{0}'>{1}</span>", htmlAttributes["style"].ToString(), separator));
            int minSecond = 0;
            int maxSecond = 59;

            if (applyRestrictionsMin)
            {
                if (min.Value.Second > minSecond)
                {
                    minSecond = min.Value.Second;
                }
            }
            else
            {
                applyRestrictionsMin = false;
            }

            if (applyRestrictionsMax)
            {
                if (max.Value.Second < maxSecond)
                {
                    maxSecond = max.Value.Second;
                }
            }
            else
            {
                applyRestrictionsMax = false;
            }

            List <SelectListItem> allSeconds = new List <SelectListItem>(1);

            for (int second = Seconds; second <= Seconds; second++)
            {
                allSeconds.Add(new SelectListItem()
                {
                    Value    = second.ToString(),
                    Text     = second.ToString("00"),
                    Selected = Seconds == second
                });
            }
            //AddFunctions(ref htmlAttributes, true);
            sb.Append(htmlHelper.DropDownList(
                          BasicHtmlHelper.AddField(newPrefix, "Seconds"),
                          allSeconds,
                          htmlAttributes).ToString());

            return(MvcHtmlString.Create(sb.ToString()));
        }
コード例 #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()));
        }
コード例 #30
0
        public MvcHtmlString Date(bool useTextBoxForYear = false, IDictionary <string, object> htmlAttributes = null, IDictionary <string, object> htmlAttributesTextBox = null, CultureInfo culture = null)
        {
            if (this.dateRendered)
            {
                return(MvcHtmlString.Create(string.Empty));
            }
            if (this.dateInCalendar)
            {
                throw new ArgumentException(ControlsResources.DateTimeInput_Combo);
            }
            dateRendered = true;
            string newPrefix = BasicHtmlHelper.AddField(prefix, "$");

            if (culture == null)
            {
                culture = CultureInfo.CurrentUICulture;
            }
            if (htmlAttributesTextBox == null)
            {
                htmlAttributesTextBox = htmlAttributes;
            }
            if (htmlAttributes == null)
            {
                htmlAttributes = new Dictionary <string, object>();
            }
            if (htmlAttributesTextBox == null)
            {
                htmlAttributesTextBox = new Dictionary <string, object>();
            }
            htmlAttributesTextBox["data-elementispart"] = "true";
            htmlAttributes["data-elementispart"]        = "true";
            DateTime?     min = currMin;
            DateTime?     max = currMax;
            StringBuilder sb  = new StringBuilder();


            BasicHtmlHelper.SetDefaultStyle(htmlAttributes, "text-align", "right");
            string sYear = string.Empty;

            if (useTextBoxForYear || min == null || !min.HasValue || max == null || !max.HasValue)
            {
                htmlAttributesTextBox["maxlength"] = "4";
                htmlAttributesTextBox["size"]      = "5";
                //AddFunctions(ref htmlAttributesTextBox, false);
                BasicHtmlHelper.SetDefaultStyle(htmlAttributesTextBox, "text-align", "right");
                BasicHtmlHelper.SetDefaultStyle(htmlAttributesTextBox, "width", "4em");
                sYear = htmlHelper.TextBox(
                    BasicHtmlHelper.AddField(newPrefix, "Year"), Year, htmlAttributesTextBox).ToString();
            }
            else
            {
                yearCombo = true;
                List <SelectListItem> allYears = new List <SelectListItem>(1);
                for (int year = Year; year <= Year; year++)
                {
                    allYears.Add(new SelectListItem()
                    {
                        Value    = year.ToString(),
                        Text     = AlignFourDigits(year),
                        Selected = Year == year
                    });
                }
                //AddFunctions(ref htmlAttributes, false);
                sYear = htmlHelper.DropDownList(
                    BasicHtmlHelper.AddField(newPrefix, "Year"),
                    allYears,
                    htmlAttributes).ToString();
            }
            sb.Append(RenderBasicScripts(culture));
            int minMonth = 1;
            int maxMonth = 12;

            if (min != null && min.HasValue && min.Value.Year == curr.Value.Year)
            {
                if (min.Value.Month > minMonth)
                {
                    minMonth = min.Value.Month;
                }
            }
            if (max != null && max.HasValue && curr.Value.Year == max.Value.Year)
            {
                if (max.Value.Month < maxMonth)
                {
                    maxMonth = max.Value.Month;
                }
            }
            List <SelectListItem> allMonths = new List <SelectListItem>(1);

            for (int month = Month; month <= Month; month++)
            {
                allMonths.Add(new SelectListItem()
                {
                    Value    = month.ToString(),
                    Text     = culture.DateTimeFormat.MonthNames[month - 1],
                    Selected = Month == month
                });
            }
            //AddFunctions(ref htmlAttributes, false);
            string sMonth = htmlHelper.DropDownList(
                BasicHtmlHelper.AddField(newPrefix, "Month"),
                allMonths,
                htmlAttributes).ToString();
            int minDay = 1;
            int maxDay = DateTime.DaysInMonth(Year, Month);

            if (min != null && min.HasValue &&
                min.Value.Year == curr.Value.Year && min.Value.Month == curr.Value.Month)
            {
                if (min.Value.Day > minDay)
                {
                    minDay = min.Value.Day;
                }
            }
            if (max != null && max.HasValue &&
                curr.Value.Year == max.Value.Year && curr.Value.Month == max.Value.Month)
            {
                if (max.Value.Day < maxDay)
                {
                    maxDay = max.Value.Day;
                }
            }
            List <SelectListItem> allDays = new List <SelectListItem>(1);

            for (int day = Day; day <= Day; day++)
            {
                allDays.Add(new SelectListItem()
                {
                    Value    = day.ToString(),
                    Text     = AlignTwoDigits(day),
                    Selected = Day == day
                });
            }
            //AddFunctions(ref htmlAttributes, true);
            string sDay = htmlHelper.DropDownList(
                BasicHtmlHelper.AddField(newPrefix, "Day"),
                allDays,
                htmlAttributes).ToString();

            char[] OrderInfo = dateOrder(culture);

            if (OrderInfo[0] == 'y')
            {
                sb.Append(sYear);
            }
            if (OrderInfo[0] == 'M')
            {
                sb.Append(sMonth);
            }
            if (OrderInfo[0] == 'd')
            {
                sb.Append(sDay);
            }

            if (OrderInfo[1] == 'y')
            {
                sb.Append(sYear);
            }
            if (OrderInfo[1] == 'M')
            {
                sb.Append(sMonth);
            }
            if (OrderInfo[1] == 'd')
            {
                sb.Append(sDay);
            }

            if (OrderInfo[2] == 'y')
            {
                sb.Append(sYear);
            }
            if (OrderInfo[2] == 'M')
            {
                sb.Append(sMonth);
            }
            if (OrderInfo[2] == 'd')
            {
                sb.Append(sDay);
            }

            return(MvcHtmlString.Create(sb.ToString()));
        }