Пример #1
0
        public static MvcHtmlString IncludeRejuicedJsFor(HtmlHelper instance, string filename)
        {
            var cachedValue = GetCachedIncludesFor(filename);
            if (cachedValue != null)
            {
                return cachedValue.RenderHtml();
            }

            var toInclude = GetIncludesFor(filename);
            var config = RejuicerEngine.GetConfigFor(filename);

            if (config == null)
            {
                return MvcHtmlString.Create("");
            }

            var dependencies = config.GetDependencies();

            var scripts = MvcHtmlString.Create(string.Join("\n", toInclude.Select(f =>
            {
                // Output <script src='' type=''>
                var script = new TagBuilder("script");
                script.Attributes.Add("src", UrlHelper.GenerateContentUrl(f, new HttpContextWrapper(HttpContext.Current)));
                script.Attributes.Add("type", "text/javascript");

                return script.ToString(TagRenderMode.Normal);
            }).ToArray()));

            var cachedIncludes = new IncludesCacheModel { IncludesHtml = scripts, HashValue = config.GetHashValue(cacheProvider) };

            SetCachedIncludesFor(filename, cachedIncludes, dependencies);

            return cachedIncludes.RenderHtml();
        }
        public void VeneerScripts_handles_content_types_with_no_scripts()
        {
            // Arrange
            var service = new Mock<IContentService>();
            var content = new Content
            {
                RefreshDate = DateTime.Now,
                Sections = new List<ContentSection>
                {
                    new ContentSection
                    {
                        Id = "Footer", Html = "<div id='hello' />", Scripts = new List<ContentScript>()
                    }
                }
            };
            service.Setup(x => x.Get(It.IsAny<ContentTypes>())).Returns(content);
            var contentTypes = new List<ContentTypes> { ContentTypes.Footer };

            var model = new VeneerBaseViewModel(service.Object, contentTypes);

            var viewContext = new ViewContext();
            var viewDataContainer = new Mock<IViewDataContainer>();
            var htmlHelper = new HtmlHelper(viewContext, viewDataContainer.Object);

            // Act
            var result = htmlHelper.VeneerScripts(model).ToHtmlString();

            // Assert
            Assert.That(result, Is.Empty);
        }
Пример #3
0
        private static void RenderPartial(HtmlHelper htmlHelper, string partialViewName, ViewDataDictionary viewData, object model, TextWriter writer)
        {
            ViewDataDictionary newViewData;
            if (model == null)
            {
                newViewData = viewData == null ? new ViewDataDictionary(htmlHelper.ViewData) : new ViewDataDictionary(viewData);
            }
            else
            {
                newViewData = viewData == null ? new ViewDataDictionary(model) : new ViewDataDictionary(viewData) { Model = model };
            }

            var controller = htmlHelper.ViewContext.Controller as Controller;
            var viewEngineCollection = controller != null ? controller.ViewEngineCollection : ViewEngines.Engines;
            var newViewContext = new ViewContext(htmlHelper.ViewContext, htmlHelper.ViewContext.View, newViewData, htmlHelper.ViewContext.TempData, writer);
            var result = viewEngineCollection.FindPartialView(newViewContext, partialViewName);
            if (result.View != null)
            {
                result.View.Render(newViewContext, writer);
            }
            else
            {
                var locationsText = new StringBuilder();
                foreach (string location in result.SearchedLocations)
                {
                    locationsText.AppendLine();
                    locationsText.Append(location);
                }

                throw new InvalidOperationException("The partial view '{0}' was not found or no view engine supports the searched locations. The following locations were searched: {1}".Arrange(partialViewName, locationsText));
            }
        }
 public BootstrapActionLink(HtmlHelper html, string linkText, ActionResult result)
 {
     this.html = html;
     this._linkText = linkText;
     this._result = result;
     this._actionTypePassed = ActionTypePassed.HtmlActionResult;
 }
 public TabStripCreated(TabFactory itemFactory, string tabStripName, HtmlHelper html, object model = null)
 {
     this.TabStripName = tabStripName;
     this.Html = html;
     this.Model = model;
     this.ItemFactory = itemFactory;
 }
Пример #6
0
 public PopUpMenu(HtmlHelper helper, string id, int minWidth = 0)
     : base(helper)
 {
     Id = id;
     MinWidth = minWidth;
     Items = new List<PopUpMenuItem>();
 }
Пример #7
0
		private static MvcHtmlString GenerateNavigationFor35Or30(HtmlHelper htmlHelper, Language language, string version)
		{
			var builder = new StringBuilder();
			builder.AppendLine("<ul class='nav navbar-nav'>");

			builder.AppendLine(string.Format("<li>{0}</li>", htmlHelper.ActionLink("Getting started", MVC.Docs.ActionNames.Articles, MVC.Docs.Name, new { language = language, version = version, key = "start/getting-started" }, null)));
			builder.AppendLine(string.Format("<li>{0}</li>", htmlHelper.ActionLink("Indexes", MVC.Docs.ActionNames.Articles, MVC.Docs.Name, new { language = language, version = version, key = "indexes/what-are-indexes" }, null)));
			builder.AppendLine(string.Format("<li>{0}</li>", htmlHelper.ActionLink("Transformers", MVC.Docs.ActionNames.Articles, MVC.Docs.Name, new { language = language, version = version, key = "transformers/what-are-transformers" }, null)));
			builder.AppendLine(string.Format("<li>{0}</li>", htmlHelper.ActionLink("Client API", MVC.Docs.ActionNames.Client, MVC.Docs.Name, new { language = language, version = version }, null)));
			builder.AppendLine(string.Format("<li>{0}</li>", htmlHelper.ActionLink("Server", MVC.Docs.ActionNames.Server, MVC.Docs.Name, new { language = language, version = version }, null)));
			builder.AppendLine(string.Format("<li>{0}</li>", htmlHelper.ActionLink("Studio", MVC.Docs.ActionNames.Articles, MVC.Docs.Name, new { language = language, version = version, key = "studio/accessing-studio" }, null)));

			builder.AppendLine("<li class='dropdown'>");
			builder.AppendLine("<a href='#' class='dropdown-toggle' data-toggle='dropdown'>Other <span class='caret'></span></a>");
			builder.AppendLine("<ul class='dropdown-menu' role='menu'>");
			builder.AppendLine(string.Format("<li>{0}</li>", htmlHelper.ActionLink("Samples", MVC.Docs.ActionNames.Samples, MVC.Docs.Name, new { language = language, version = version }, null)));
			builder.AppendLine(string.Format("<li>{0}</li>", htmlHelper.ActionLink("Glossary", MVC.Docs.ActionNames.Glossary, MVC.Docs.Name, new { language = language, version = version }, null)));
			builder.AppendLine(string.Format("<li>{0}</li>", htmlHelper.ActionLink("Users Issues", MVC.Docs.ActionNames.Articles, MVC.Docs.Name, new { language = language, version = version, key = "users-issues/azure-router-timeout" }, null)));
			builder.AppendLine("</ul>");
			builder.AppendLine("</li>");

			builder.AppendLine(string.Format("<li>{0}</li>", htmlHelper.ActionLink("File System", MVC.Docs.ActionNames.FileSystem, MVC.Docs.Name, new { language = language, version = version, key = "file-system/what-is-ravenfs" }, null)));

			builder.AppendLine("</ul>");

			return new MvcHtmlString(builder.ToString());
		}
Пример #8
0
        public Displayable(HtmlHelper helper, string propertyName, ContentItem currentItem)
            : base(helper, currentItem)
        {
            if (propertyName == null) throw new ArgumentNullException("propertyName");

            this.propertyName = propertyName;
        }
Пример #9
0
 public ListBox(HtmlHelper html, string htmlFieldName, IEnumerable<SelectListItem> selectList, ModelMetadata metadata)
 {
     this.html = html;
     this._model.htmlFieldName = htmlFieldName;
     this._model.selectList = selectList;
     this._model.metadata = metadata;
 }
Пример #10
0
 private static IDictionary<string, MvcHtmlString> GetFlashMessages(HtmlHelper helper, string sessionKey)
 {
     sessionKey = "Flash." + sessionKey;
     return (helper.ViewContext.TempData[sessionKey] != null
                 ? (IDictionary<string, MvcHtmlString>)helper.ViewContext.TempData[sessionKey]
                 : null);
 }
 public BootstrapRadioButton(HtmlHelper html, string htmlFieldName, object value, ModelMetadata metadata)
 {
     this.html = html;
     this._model.htmlFieldName = htmlFieldName;
     this._model.value = value;
     this._model.metadata = metadata;
 }
            public void WritesCollectionIndexHiddenInput_WhenThereIsNothingInRequestData()
            {
                const string collectionName = "CollectionName";
                var httpContext = new Mock<HttpContextBase>();
                var httpContextItems = new Dictionary<string, object>();
                httpContext.Setup(p => p.Items).Returns(httpContextItems);

                var httpRequest = new Mock<HttpRequestBase>();
                httpContext.Setup(p => p.Request).Returns(httpRequest.Object);

                var viewContext = new ViewContext();
                var writer = new StringWriter();
                viewContext.Writer = writer;

                var html = new HtmlHelper(viewContext, new FakeViewDataContainer());
                viewContext.HttpContext = httpContext.Object;

                using (var result = html.BeginCollectionItem(collectionName))
                {
                    Assert.That(result, Is.Not.Null);
                }

                var text = writer.ToString();
                Assert.That(text,
                            Is.Not.Null
                              .And.Not.Empty
                              .And.StartsWith(string.Format(@"<input type=""hidden"" name=""{0}.index"" autocomplete=""off"" value=""", collectionName))
                              .And.Contains(@""" />"));
            }
            public void WritesExpectedCollectionIndexHiddenInput_WhenThereIsAnIndexInRequestData()
            {
                const string collectionName = "CollectionName";
                var index0 = Guid.NewGuid();
                var index1 = Guid.NewGuid();
                var indexes = string.Format("{0},{1}", index0, index1);
                var httpContext = new Mock<HttpContextBase>();
                var httpContextItems = new Dictionary<string, object>();
                httpContext.Setup(p => p.Items).Returns(httpContextItems);

                var httpRequest = new Mock<HttpRequestBase>();
                httpRequest.Setup(i => i[It.Is<string>(s => s == string.Format("{0}.index", collectionName))])
                    .Returns(indexes);
                httpContext.Setup(p => p.Request).Returns(httpRequest.Object);

                var viewContext = new ViewContext();
                var writer = new StringWriter();
                viewContext.Writer = writer;

                var html = new HtmlHelper(viewContext, new FakeViewDataContainer());
                viewContext.HttpContext = httpContext.Object;

                using (var result = html.BeginCollectionItem(collectionName))
                {
                    Assert.That(result, Is.Not.Null);
                }

                var text = writer.ToString();
                Assert.That(text,
                            Is.Not.Null
                              .And.Not.Empty
                              .And.StringStarting(string.Format(@"<input type=""hidden"" name=""{0}.index"" autocomplete=""off"" value=""{1}"" />", collectionName, index0)));
            }
Пример #14
0
 public FrontHtmlHelper(Page_Context context, HtmlHelper html, ViewRender viewRender, ProxyRender proxyRender)
 {
     this.PageContext = context;
     this.Html = html;
     this.ViewRender = viewRender;
     this.ProxyRender = proxyRender;
 }
Пример #15
0
        /// <summary>
        /// Creates new instance of scope, here writer is replaced
        /// </summary>
        /// <param name="helper">Helper where writer shoud be replaced</param>
        /// <param name="writer">Writer to use in place</param>
        public WriterScope(HtmlHelper helper, TextWriter writer)
        {
            _helper = helper;
            _original = _helper.ViewContext.Writer;

            _helper.ViewContext.Writer = writer;
        }
Пример #16
0
        public static IHtmlString Render(string alias, HtmlHelper<RenderModel> helper)
        {

            try
            {
                // If request is coming from frontend then always show frontend content, check authentication if it comes from backend (.aspx)

                var isAuthenticated = false;

                if (HttpContext.Current.Request.Path.Contains(".aspx"))
                {
                    isAuthenticated = Authorize.isAuthenticated();
                }

                var view = ViewHelper.Get(alias, isAuthenticated);

                var culture = CultureInfo.CreateSpecificCulture(UmbracoContext.Current.PublishedContentRequest.Culture.Name);

                Thread.CurrentThread.CurrentCulture = culture;
                Thread.CurrentThread.CurrentUICulture = culture;

                var model = helper.Partial(view.viewName, view);

                return new HtmlString(model.ToString());

            }
            catch (Exception ex)
            {

                Log.Error("Canvas Error on Render in API.", ex);
                return new HtmlString("");

            }

        }
Пример #17
0
        public Pager(HtmlHelper htmlHelper, int pageSize, int currentPage, int totalItemCount, RouteValueDictionary valuesDictionary, string labelPrevious, string labelNext)
            : this()
        {
            this._htmlHelper = htmlHelper;
            this.pageSize = pageSize;
            this.currentPage = currentPage;
            this.totalItemCount = totalItemCount;
            this.linkWithoutPageValuesDictionary = valuesDictionary;
            var queryString = htmlHelper.ViewContext.RequestContext.HttpContext.Request.QueryString;
            //if (queryString.Count > 0)
            //{
            //    //Add querystring into routevalues.
            //    foreach (var key in queryString.Keys)
            //    {
            //        if (!valuesDictionary.ContainsKey(key))
            //        {
            //            valuesDictionary.Add(key, queryString[key]);
            //        }
            //    }
            //}

            if (labelPrevious != null)
            {
                this.LabelPrevious = labelPrevious;
            }
            if (labelNext != null)
            {
                this.LabelNext = labelNext;
            }
        }
 /// <summary>
 /// The container breaks the slider content, and we do not need it,
 /// since we won't edit the content when using this renderer
 /// </summary>
 /// <param name="htmlHelper"></param>
 /// <param name="contentArea"></param>
 public virtual void RenderWithoutContainer(HtmlHelper htmlHelper, ContentArea contentArea)
 {
     if ((contentArea != null) && !contentArea.IsEmpty)
     {
         RenderContentAreaItems(htmlHelper, contentArea.FilteredItems);
     }
 }
        protected override string GetContentAreaItemCssClass(HtmlHelper htmlHelper, ContentAreaItem contentAreaItem)
        {
            var childrenCssClass = htmlHelper.ViewData["ChildrenCssClass"];
            if(childrenCssClass != null)
            {
                return childrenCssClass.ToString();
            }

            var tag = GetContentAreaItemTemplateTag(htmlHelper, contentAreaItem);

            var content = contentAreaItem.GetContent(ContentRepository);
            if(content != null)
            {
                if (tag == null )
                {
                    // Let block decide what to use as default if not
                    // specified on the content area itself
                    tag = GetDefaultDisplayOption(content);
                    if (tag == null)
                    {
                        // Default is always the smalles one we've got
                        tag = WebGlobal.ContentAreaTags.OneThirdWidth;
                    }
                }
                htmlHelper.ViewContext.ViewData["Tag"] = tag;
                return string.Format("block {0} {1} {2}",
                    GetTypeSpecificCssClasses(content),
                    GetCssClassForTag(tag),
                    tag);
            }
            else
            {
                return WebGlobal.ContentAreaTags.NoRenderer;
            }
        }
Пример #20
0
        public static MvcHtmlString RenderContent(HtmlHelper helper, TypeContext typeContext, RenderContentMode mode, EntityBase line)
        {
            TypeContext tc = TypeContextUtilities.CleanTypeContext((TypeContext)typeContext);

            ViewDataDictionary vdd = GetViewData(helper, line, tc);
            
            string partialViewName = line.PartialViewName ?? OnPartialViewName(tc);

            switch (mode)
            {
                case RenderContentMode.Content:
                    return helper.Partial(partialViewName, vdd);

                case RenderContentMode.ContentInVisibleDiv:
                    return helper.Div(typeContext.Compose(EntityBaseKeys.Entity),
                      helper.Partial(partialViewName, vdd), "",
                      null);
                case RenderContentMode.ContentInInvisibleDiv:
                    return helper.Div(typeContext.Compose(EntityBaseKeys.Entity),
                        helper.Partial(partialViewName, vdd), "",
                         new Dictionary<string, object> { { "style", "display:none" } });
                default:
                    throw new InvalidOperationException();
            }
        }
        public void DisplayNameConsultsMetadataProviderForMetadataAboutProperty()
        {
            // Arrange
            Model model = new Model { PropertyName = "propertyValue" };

            ViewDataDictionary viewData = new ViewDataDictionary();
            Mock<ViewContext> viewContext = new Mock<ViewContext>();
            viewContext.Setup(c => c.ViewData).Returns(viewData);

            Mock<IViewDataContainer> viewDataContainer = new Mock<IViewDataContainer>();
            viewDataContainer.Setup(c => c.ViewData).Returns(viewData);

            HtmlHelper<Model> html = new HtmlHelper<Model>(viewContext.Object, viewDataContainer.Object);
            viewData.Model = model;

            MetadataHelper metadataHelper = new MetadataHelper();

            metadataHelper.MetadataProvider.Setup(p => p.GetMetadataForProperty(It.IsAny<Func<object>>(), typeof(Model), "PropertyName"))
                .Returns(metadataHelper.Metadata.Object)
                .Verifiable();

            // Act
            html.DisplayNameInternal("PropertyName", metadataHelper.MetadataProvider.Object);

            // Assert
            metadataHelper.MetadataProvider.Verify();
        }
Пример #22
0
        public static string BuildContent(HtmlHelper html, string Content)
        {
            var matches = Regex.Matches(Content, "<img.+?src=[\"'](.+?)[\"'].*?>", RegexOptions.IgnoreCase);
            foreach (Match match in matches)
            {
                string url = match.Groups[1].Value;
                if (!url.Contains("cid"))
                {

                    string imagetagstr = Postal.HtmlExtensions.EmbedImage(html, url, "").ToHtmlString();
                    string newcid = Regex.Match(imagetagstr, "<img.+?src=[\"'](.+?)[\"'].*?>", RegexOptions.IgnoreCase).Groups[1].Value;
                    Content = Content.Replace(url, newcid);
                }
            }

            matches = Regex.Matches(Content, @"background:url\('(?<bgpath>.*)'\)", RegexOptions.IgnoreCase);
            foreach (Match match in matches)
            {
                string url = match.Groups[1].Value;
                if (!url.Contains("cid"))
                {
                    string imagetagstr = Postal.HtmlExtensions.EmbedImage(html, url, "").ToHtmlString();
                    string newcid = Regex.Match(imagetagstr, "<img.+?src=[\"'](.+?)[\"'].*?>", RegexOptions.IgnoreCase).Groups[1].Value;

                    Content = Content.Replace(url, newcid);
                }
            }
            return Content;
        }
Пример #23
0
        public static string RenderSitecorePlaceHolder(string key)
        {
            var sublayoutId = GetSublayoutIdFromPlaceHolder(Sitecore.Context.Item[Sitecore.FieldIDs.LayoutField], key);
            if (!string.IsNullOrEmpty(sublayoutId))
            {
                var layoutItem = Sitecore.Context.Database.GetItem(ID.Parse(sublayoutId));
                var controllerName = layoutItem.Fields["Controller"].Value;
                var actionName = layoutItem.Fields["Action"].Value;

                HttpContext.Current.RewritePath(string.Concat("/", controllerName, "/", actionName));

                RouteData routeData = RouteTable.Routes.GetRouteData(new HttpContextWrapper(HttpContext.Current));
                if (routeData != null)
                {
                    var factory = new ControllerFactory();
                    var httpContextBase = new HttpContextWrapper(HttpContext.Current);
                    var context = new RequestContext(httpContextBase, routeData);
                    Type type = factory.GetController(context, controllerName);

                    if (type != null)
                    {
                        var controller = (Controller)factory.GetController(context, type);

                        var controllerContext = new ControllerContext(httpContextBase, routeData, controller);
                        var viewContext = new ViewContext(controllerContext, new FakeView(), controller.ViewData, controller.TempData, TextWriter.Null);

                        var helper = new HtmlHelper(viewContext, new ViewPage());

                        return helper.Action(actionName, controllerName).ToHtmlString();
                    }
                }
                HttpContext.Current.RewritePath("default.aspx");
            }
            return "";
        }
Пример #24
0
        public static MvcHtmlString RenderComponentPresentations(HtmlHelper helper, string[] byComponentTemplate, string bySchema, IComponentPresentationRenderer renderer)
        {
            _logger.Information(">>RenderComponentPresentations", LoggingCategory.Performance);
            IComponentPresentationRenderer cpr = renderer;
            IPage page = null;
            if (helper.ViewData.Model is IPage)
            {
                page = helper.ViewData.Model as IPage;
            }
            else
            {
                try
                {
                    page = helper.ViewContext.Controller.ViewBag.Page;
                }
                catch
                {
                    return new MvcHtmlString("<!-- RenderComponentPresentations can only be used if the model is an instance of IPage or if there is a Page property in the viewbag with type IPage -->");
                }
            }

            if (renderer == null)
            {
                _logger.Debug("about to create DefaultComponentPresentationRenderer", LoggingCategory.Performance);
                renderer = _renderer;
                _logger.Debug("finished creating DefaultComponentPresentationRenderer", LoggingCategory.Performance);
            }

            _logger.Debug("about to call renderer.ComponentPresentations", LoggingCategory.Performance);
            MvcHtmlString output = renderer.ComponentPresentations(page, helper, byComponentTemplate, bySchema);
            _logger.Debug("finished calling renderer.ComponentPresentations", LoggingCategory.Performance);
            _logger.Information("<<RenderComponentPresentations", LoggingCategory.Performance);

            return output;
        }
Пример #25
0
 /// <summary>
 /// Render an entity (Component Presentation)
 /// </summary>
 /// <param name="item">The Component Presentation object</param>
 /// <param name="helper">The HTML Helper</param>
 /// <param name="containerSize">The size of the containing element (in grid units)</param>
 /// <param name="excludedItems">A list of view names, if the Component Presentation maps to one of these, it is skipped.</param>
 /// <returns>The rendered content</returns>
 public override MvcHtmlString RenderEntity(object item, HtmlHelper helper, int containerSize = 0, List<string> excludedItems = null)
 {
     var cp = item as IComponentPresentation;
     var mvcData = ContentResolver.ResolveMvcData(cp);
     if (cp != null && (excludedItems == null || !excludedItems.Contains(mvcData.ViewName)))
     {
         var parameters = new RouteValueDictionary();
         int parentContainerSize = helper.ViewBag.ContainerSize;
         if (parentContainerSize == 0)
         {
             parentContainerSize = SiteConfiguration.MediaHelper.GridSize;
         }
         if (containerSize == 0)
         {
             containerSize = SiteConfiguration.MediaHelper.GridSize;
         }
         parameters["containerSize"] = (containerSize * parentContainerSize) / SiteConfiguration.MediaHelper.GridSize;
         parameters["entity"] = cp;
         parameters["area"] = mvcData.ControllerAreaName;
         foreach (var key in mvcData.RouteValues.Keys)
         {
             parameters[key] = mvcData.RouteValues[key];
         }
         MvcHtmlString result = helper.Action(mvcData.ActionName, mvcData.ControllerName, parameters);
         if (WebRequestContext.IsPreview)
         {
             result = new MvcHtmlString(TridionMarkup.ParseEntity(result.ToString()));
         }
         return result;
     }
     return null;
 }
 public BootstrapActionLink(HtmlHelper html, string linkText, string actionName)
 {
     this.html = html;
     this._linkText = linkText;
     this._actionName = actionName;
     this._actionTypePassed = ActionTypePassed.HtmlRegular;
 }
Пример #27
0
 internal PagerBuilder(HtmlHelper html, AjaxHelper ajax, string actionName, string controllerName,
     int totalPageCount, int pageIndex, PagerOptions pagerOptions, string routeName, RouteValueDictionary routeValues,
     MvcAjaxOptions ajaxOptions, IDictionary<string, object> htmlAttributes)
 {
     _ajaxPagingEnabled = (ajax != null);
     if (pagerOptions == null)
         pagerOptions = new PagerOptions();
     _html = html;
     _ajax = ajax;
     _actionName = actionName;
     _controllerName = controllerName;
     if (pagerOptions.MaxPageIndex == 0 || pagerOptions.MaxPageIndex > totalPageCount)
         _totalPageCount = totalPageCount;
     else
         _totalPageCount = pagerOptions.MaxPageIndex;
     _pageIndex = pageIndex;
     _pagerOptions = pagerOptions;
     _routeName = routeName;
     _routeValues = routeValues;
     _ajaxOptions = ajaxOptions;
     _htmlAttributes = htmlAttributes;
     // start page index
     _startPageIndex = pageIndex - (pagerOptions.NumericPagerItemCount / 2);
     if (_startPageIndex + pagerOptions.NumericPagerItemCount > _totalPageCount)
         _startPageIndex = _totalPageCount + 1 - pagerOptions.NumericPagerItemCount;
     if (_startPageIndex < 1)
         _startPageIndex = 1;
     // end page index
     _endPageIndex = _startPageIndex + _pagerOptions.NumericPagerItemCount - 1;
     if (_endPageIndex > _totalPageCount)
         _endPageIndex = _totalPageCount;
 }
Пример #28
0
        public static IEnumerable<SelectListItem> GetSelectListItems(HtmlHelper html, ISelectListBuilder dropDownList, string expressionText)
        {
            string fullHtmlFieldName = html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(expressionText);

            bool flag = false;

            IEnumerable<SelectListItem> selectList = dropDownList.SelectList();
            bool allowMultiple = dropDownList.Attr("multiple") == "multiple";

            if (selectList == null)
            {
                selectList = html.GetSelectListItemsFromViewData(expressionText);
                flag = true;
            }
            object defaultValue = allowMultiple ? html.GetModelStateValue(fullHtmlFieldName, typeof(string[])) : html.GetModelStateValue(fullHtmlFieldName, typeof(string));
            if (!flag && defaultValue == null && !String.IsNullOrEmpty(expressionText))
            {
                defaultValue = html.ViewData.Eval(expressionText);
            }
            if (defaultValue != null)
            {
                selectList = GetSelectListWithDefaultValue(selectList, defaultValue, allowMultiple);
            }
            return selectList;
        }
 public BootstrapActionLink(HtmlHelper html, string linkText, Task<ActionResult> taskResult)
 {
     this.html = html;
     this._linkText = linkText;
     this._taskResult = taskResult;
     this._actionTypePassed = ActionTypePassed.HtmlTaskResult;
 }
Пример #30
0
        public static MvcHtmlString RenderPopup(HtmlHelper helper, TypeContext typeContext, RenderPopupMode mode, EntityBase line, bool isTemplate = false)
        {
            TypeContext tc = TypeContextUtilities.CleanTypeContext((TypeContext)typeContext);

            ViewDataDictionary vdd = GetViewData(helper, line, tc);

            string partialViewName = line.PartialViewName ?? OnPartialViewName(tc);

            vdd[ViewDataKeys.PartialViewName] = partialViewName;
            vdd[ViewDataKeys.ViewMode] = !line.ReadOnly;
            vdd[ViewDataKeys.ViewMode] = ViewMode.View;
            vdd[ViewDataKeys.ShowOperations] = true;
            vdd[ViewDataKeys.SaveProtected] = OperationLogic.IsSaveProtected(tc.UntypedValue.GetType());
            vdd[ViewDataKeys.WriteEntityState] = 
                !isTemplate &&
                !(tc.UntypedValue is EmbeddedEntity) &&
                ((ModifiableEntity)tc.UntypedValue).Modified == ModifiedState.SelfModified;

            switch (mode)
            {
                case RenderPopupMode.Popup:
                    return helper.Partial(Navigator.Manager.PopupControlView, vdd);
                case RenderPopupMode.PopupInDiv:
                    return helper.Div(typeContext.Compose(EntityBaseKeys.Entity),
                        helper.Partial(Navigator.Manager.PopupControlView, vdd),  
                        "",
                        new Dictionary<string, object> { { "style", "display:none" } });
                default:
                    throw new InvalidOperationException();
            }
        }
Пример #31
0
 /// <summary>
 /// Append canonical URL element to the <![CDATA[<head>]]>
 /// </summary>
 /// <param name="html">HTML helper</param>
 /// <param name="part">Canonical URL part</param>
 public static void AppendCanonicalUrlParts(this HtmlHelper html, string part)
 {
     var pageHeadBuilder = EngineContext.Current.Resolve<IPageHeadBuilder>();
     pageHeadBuilder.AppendCanonicalUrlParts(part);
 }
Пример #32
0
 /// <summary>
 /// Add meta keyword element to the <![CDATA[<head>]]>
 /// </summary>
 /// <param name="html">HTML helper</param>
 /// <param name="part">Meta keyword part</param>
 public static void AddMetaKeywordParts(this HtmlHelper html, string part)
 {
     var pageHeadBuilder = EngineContext.Current.Resolve<IPageHeadBuilder>();
     pageHeadBuilder.AddMetaKeywordParts(part);
 }
Пример #33
0
 /// <summary>
 /// Generate all description parts
 /// </summary>
 /// <param name="html">HTML helper</param>
 /// <param name="part">Meta description part</param>
 /// <returns>Generated string</returns>
 public static MvcHtmlString NopMetaDescription(this HtmlHelper html, string part = "")
 {
     var pageHeadBuilder = EngineContext.Current.Resolve<IPageHeadBuilder>();
     html.AppendMetaDescriptionParts(part);
     return MvcHtmlString.Create(html.Encode(pageHeadBuilder.GenerateMetaDescription()));
 }
Пример #34
0
 /// <summary>
 /// Append meta description element to the <![CDATA[<head>]]>
 /// </summary>
 /// <param name="html">HTML helper</param>
 /// <param name="part">Meta description part</param>
 public static void AppendMetaDescriptionParts(this HtmlHelper html, string part)
 {
     var pageHeadBuilder = EngineContext.Current.Resolve<IPageHeadBuilder>();
     pageHeadBuilder.AppendMetaDescriptionParts(part);
 }
Пример #35
0
 /// <summary>
 /// Generate all title parts
 /// </summary>
 /// <param name="html">HTML helper</param>
 /// <param name="addDefaultTitle">A value indicating whether to insert a default title</param>
 /// <param name="part">Title part</param>
 /// <returns>Generated string</returns>
 public static MvcHtmlString NopTitle(this HtmlHelper html, bool addDefaultTitle, string part = "")
 {
     var pageHeadBuilder = EngineContext.Current.Resolve<IPageHeadBuilder>();
     html.AppendTitleParts(part);
     return MvcHtmlString.Create(html.Encode(pageHeadBuilder.GenerateTitle(addDefaultTitle)));
 }
Пример #36
0
 /// <summary>
 /// Generate all custom elements
 /// </summary>
 /// <param name="html">HTML helper</param>
 /// <returns>Generated string</returns>
 public static MvcHtmlString NopHeadCustom(this HtmlHelper html)
 {
     var pageHeadBuilder = EngineContext.Current.Resolve<IPageHeadBuilder>();
     return MvcHtmlString.Create(pageHeadBuilder.GenerateHeadCustom());
 }
Пример #37
0
 /// <summary>
 /// Generate all canonical URL parts
 /// </summary>
 /// <param name="html">HTML helper</param>
 /// <param name="part">Canonical URL part</param>
 /// <returns>Generated string</returns>
 public static MvcHtmlString NopCanonicalUrls(this HtmlHelper html, string part = "")
 {
     var pageHeadBuilder = EngineContext.Current.Resolve<IPageHeadBuilder>();
     html.AppendCanonicalUrlParts(part);
     return MvcHtmlString.Create(pageHeadBuilder.GenerateCanonicalUrls());
 }
Пример #38
0
 /// <summary>
 /// Append CSS element
 /// </summary>
 /// <param name="html">HTML helper</param>
 /// <param name="location">A location of the script element</param>
 /// <param name="part">CSS part</param>
 public static void AppendCssFileParts(this HtmlHelper html, ResourceLocation location, string part)
 {
     var pageHeadBuilder = EngineContext.Current.Resolve<IPageHeadBuilder>();
     pageHeadBuilder.AppendCssFileParts(location, part);
 }
Пример #39
0
 /// <summary>
 /// Append script element
 /// </summary>
 /// <param name="html">HTML helper</param>
 /// <param name="location">A location of the script element</param>
 /// <param name="part">Script part</param>
 /// <param name="excludeFromBundle">A value indicating whether to exclude this script from bundling</param>
 public static void AppendScriptParts(this HtmlHelper html, ResourceLocation location, string part, bool excludeFromBundle = false)
 {
     var pageHeadBuilder = EngineContext.Current.Resolve<IPageHeadBuilder>();
     pageHeadBuilder.AppendScriptParts(location, part, excludeFromBundle);
 }
Пример #40
0
 /// <summary>
 /// Generate all CSS parts
 /// </summary>
 /// <param name="html">HTML helper</param>
 /// <param name="urlHelper">URL Helper</param>
 /// <param name="location">A location of the script element</param>
 /// <param name="bundleFiles">A value indicating whether to bundle script elements</param>
 /// <returns>Generated string</returns>
 public static MvcHtmlString NopCssFiles(this HtmlHelper html, UrlHelper urlHelper,
     ResourceLocation location, bool? bundleFiles = null)
 {
     var pageHeadBuilder = EngineContext.Current.Resolve<IPageHeadBuilder>();
     return MvcHtmlString.Create(pageHeadBuilder.GenerateCssFiles(urlHelper, location, bundleFiles));
 }
Пример #41
0
        /// <summary>
        ///     Renders the specified partial view with the parent's view data and model if the given setting entry is found and
        ///     represents the equivalent of true.
        /// </summary>
        /// <param name="htmlHelper"></param>
        /// <param name="partialViewName">The name of the partial view.</param>
        /// <param name="appSetting">The key value of the entry point to look for.</param>
        public static void RenderPartialIf(this HtmlHelper htmlHelper, string partialViewName, string appSetting)
        {
            var setting = Settings.GetValue <bool>(appSetting);

            htmlHelper.RenderPartialIf(partialViewName, setting);
        }
Пример #42
0
 /// <summary>
 /// Append CSS element
 /// </summary>
 /// <param name="html">HTML helper</param>
 /// <param name="part">CSS part</param>
 public static void AppendCssFileParts(this HtmlHelper html, string part)
 {
     AppendCssFileParts(html, ResourceLocation.Head, part);
 }
Пример #43
0
        public static string Pager(this HtmlHelper helper, string routeName, string actionName, string controllerName, IDictionary <string, object> values, string pageParamName, bool appendQueryString, int pageCount, int noOfPageToShow, int noOfPageInEdge, int currentPage)
        {
            Func <string, int, string> getPageLink = (text, page) =>
            {
                RouteValueDictionary newValues = new RouteValueDictionary();

                foreach (KeyValuePair <string, object> pair in values)
                {
                    Guid t;
                    if ((string.Compare(pair.Key, "controller", StringComparison.OrdinalIgnoreCase) != 0) &&
                        (string.Compare(pair.Key, "action", StringComparison.OrdinalIgnoreCase) != 0) &&
                        Guid.TryParse(pair.Key, out t) == false)
                    {
                        newValues[pair.Key] = pair.Value;
                    }
                }

                if (page > 0)
                {
                    newValues[pageParamName] = page;
                }

                if (appendQueryString)
                {
                    NameValueCollection queryString = helper.ViewContext.HttpContext.Request.QueryString;

                    foreach (string key in queryString)
                    {
                        if (key != null)
                        {
                            if (!newValues.ContainsKey(key))
                            {
                                if (!string.IsNullOrEmpty(queryString[key]))
                                {
                                    newValues[key] = queryString[key];
                                }
                            }
                        }
                    }
                }

                string link;

                if (!string.IsNullOrEmpty(routeName))
                {
                    link = helper.RouteLink(text, routeName, newValues).ToHtmlString();
                }
                else
                {
                    actionName     = actionName ?? values["action"].ToString();
                    controllerName = controllerName ?? values["controller"].ToString();

                    link = helper.ActionLink(text, actionName, controllerName, newValues, null).ToHtmlString();
                }

                return(string.Concat(" ", link));
            };

            var pagerHtml = new StringBuilder();

            if (pageCount > 1)
            {
                pagerHtml.Append("<div class=\"pager\">");

                double half = Math.Ceiling(Convert.ToDouble(Convert.ToDouble(noOfPageToShow) / 2));

                int start = Convert.ToInt32((currentPage > half) ? Math.Max(Math.Min((currentPage - half), (pageCount - noOfPageToShow)), 0) : 0);
                int end   = Convert.ToInt32((currentPage > half) ? Math.Min(currentPage + half, pageCount) : Math.Min(noOfPageToShow, pageCount));

                //if (currentPage > 1)
                //{
                //    pagerHtml.Append(getPageLink("Previous", currentPage - 1));
                //}
                //else
                //{
                //    pagerHtml.Append(" <span class=\"disabled\">Previous</span>");
                //}

                if (start > 0)
                {
                    int startingEnd = Math.Min(noOfPageInEdge, start);

                    for (int i = 0; i < startingEnd; i++)
                    {
                        int pageNo = (i + 1);

                        pagerHtml.Append(getPageLink(pageNo.ToString(Constants.CurrentCulture), pageNo));
                    }

                    if (noOfPageInEdge < start)
                    {
                        pagerHtml.Append("<span>...</span>");
                    }
                }

                for (int i = start; i < end; i++)
                {
                    int pageNo = (i + 1);

                    if (pageNo == currentPage)
                    {
                        pagerHtml.Append(" <span class=\"active\">{0}</span>".FormatWith(pageNo));
                    }
                    else
                    {
                        pagerHtml.Append(getPageLink(pageNo.ToString(Constants.CurrentCulture), pageNo));
                    }
                }

                if (end < pageCount)
                {
                    if ((pageCount - noOfPageInEdge) > end)
                    {
                        pagerHtml.Append("<span>...</span>");
                    }

                    int endingStart = Math.Max(pageCount - noOfPageInEdge, end);

                    for (int i = endingStart; i < pageCount; i++)
                    {
                        int pageNo = (i + 1);
                        pagerHtml.Append(getPageLink(pageNo.ToString(Constants.CurrentCulture), pageNo));
                    }
                }

                //if (currentPage < pageCount)
                //{
                //    pagerHtml.Append(getPageLink("Next", currentPage + 1));
                //}
                //else
                //{
                //    pagerHtml.Append(" <span class=\"disabled\">Next</span>");
                //}

                pagerHtml.Append("</div>");
            }

            return(pagerHtml.ToString());
        }
Пример #44
0
 /// <summary>
 /// Append script element
 /// </summary>
 /// <param name="html">HTML helper</param>
 /// <param name="part">Script part</param>
 /// <param name="excludeFromBundle">A value indicating whether to exclude this script from bundling</param>
 public static void AppendScriptParts(this HtmlHelper html, string part, bool excludeFromBundle = false)
 {
     AppendScriptParts(html, ResourceLocation.Head, part, excludeFromBundle);
 }
Пример #45
0
        public static string StoryListPager(this HtmlHelper helper)
        {
            StoryListViewData viewData = (StoryListViewData)helper.ViewContext.ViewData.Model;

            return(Pager(helper, null, null, null, helper.ViewContext.RouteData.Values, "page", true, viewData.PageCount, 5, 2, viewData.CurrentPage));
        }
Пример #46
0
        public static MvcHtmlString EncodedActionLink(this HtmlHelper htmlHelper, IHtmlString linkText, string actionName, string controllerName, string areaName, object routeValues, object htmlAttributes)
        {
            string queryString          = string.Empty;
            string htmlAttributesString = string.Empty;
            string deployName           = ConfigurationManager.AppSettings["Deploy_Name"];

            if (routeValues != null)
            {
                RouteValueDictionary d = new RouteValueDictionary(routeValues);
                for (int i = 0; i < d.Keys.Count; i++)
                {
                    if (i > 0)
                    {
                        queryString += "?";
                    }
                    queryString += d.Keys.ElementAt(i) + "=" + d.Values.ElementAt(i);
                }
            }

            if (htmlAttributes != null)
            {
                RouteValueDictionary d = new RouteValueDictionary(htmlAttributes);
                for (int i = 0; i < d.Keys.Count; i++)
                {
                    htmlAttributesString += " " + d.Keys.ElementAt(i) + "=" + d.Values.ElementAt(i);
                }
            }

            StringBuilder ancor = new StringBuilder();

            ancor.Append("<a ");
            if (htmlAttributesString != string.Empty)
            {
                ancor.Append(htmlAttributesString);
            }
            ancor.Append(" href='");

            if (!String.IsNullOrEmpty(deployName))
            {
                ancor.Append("/" + deployName);
            }

            if (areaName != string.Empty)
            {
                ancor.Append("/" + areaName);
            }
            if (controllerName != string.Empty)
            {
                ancor.Append("/" + controllerName);
            }
            if (actionName != "Index")
            {
                ancor.Append("/" + actionName);
            }
            if (queryString != string.Empty)
            {
                ancor.Append("?q=" + Encrypt(queryString));
            }
            ancor.Append("'");
            ancor.Append(">");
            ancor.Append(linkText);
            ancor.Append("</a>");

            return(new MvcHtmlString(ancor.ToString()));
        }
Пример #47
0
        public static MvcHtmlString ModeWidgetLabels <TModel>(this HtmlHelper <TModel> html, bool mode)
        {
            var strLabel = mode ? "Ajouter" : "Modifier";

            return(MvcHtmlString.Create(strLabel));
        }
Пример #48
0
 public static MvcHtmlString Translated(this HtmlHelper helper, string id)
 {
     return(MvcHtmlString.Create(Properties.Resource1.ResourceManager.GetString(id)));
 }
Пример #49
0
        /// <summary>
        /// Create combo date selector for date time.
        /// </summary>
        /// <exception cref="ArgumentNullException">
        /// When expression is null.
        /// </exception>
        /// <typeparam name="TModel">Type of model.</typeparam>
        /// <param name="htmlHelper">HtmlHelper.</param>
        /// <param name="expression">Property selector expression.</param>
        /// <param name="yearRange">Range of years.</param>
        /// <param name="htmlAttributes">Html attributes to add to combo date.</param>
        /// <returns>Combo date selector.</returns>
        public static MvcHtmlString ComboDateFor <TModel>(
            this HtmlHelper <TModel> htmlHelper,
            Expression <Func <TModel, DateTime> > expression,
            IEnumerable <int> yearRange,
            object htmlAttributes)

        {
            if (expression == null)
            {
                throw new ArgumentNullException(nameof(expression));
            }

            string comboDateCss      = "combo-date";
            string dayContainerCss   = "day-container";
            string monthContainerCss = "month-container";
            string yearContainerCss  = "year-container";
            string errorCss          = "combo-date__error";

            string dayText   = "Gün";
            string monthText = "Ay";
            string yearText  = "İl";

            // Initialize yearRange if has not been provided
            if (yearRange == null)
            {
                yearRange = Enumerable.Range(1900, 200);
            }

            // Get model metadata
            ModelMetadata metadata = ModelMetadata.FromLambdaExpression(
                expression,
                htmlHelper.ViewData);

            string modelName = ExpressionHelper.GetExpressionText(expression);

            // Append HtmlFieldPrefix if there is any
            string fieldPrefix = htmlHelper.ViewData.TemplateInfo.HtmlFieldPrefix;

            if (!string.IsNullOrEmpty(fieldPrefix))
            {
                modelName = string.Format("{0}.{1}", fieldPrefix, modelName);
            }

            // Convert html attributes
            RouteValueDictionary attributes = HtmlHelper
                                              .AnonymousObjectToHtmlAttributes(htmlAttributes);

            // Initialize container div
            FluentTagBuilder comboDate = new FluentTagBuilder("div")
                                         .MergeAttributes(attributes)
                                         .AddCssClass(comboDateCss);

            // Initialize hidden text box for client side validation
            FluentTagBuilder input = new FluentTagBuilder("input")
                                     .MergeAttribute("name", modelName)
                                     .MergeAttribute("id", modelName)
                                     .MergeAttribute("type", "date")
                                     .MergeAttribute("hidden", "hidden")
                                     .MergeAttribute("readonly", "readonly");

            if (metadata.Model != null)
            {
                DateTime value = Convert.ToDateTime(metadata.Model);
                input.MergeAttribute("value", value.ToString("yyyy-MM-dd"));
            }

            //// Get validation attributes
            IDictionary <string, object> validationAttributes =
                htmlHelper.GetUnobtrusiveValidationAttributes(modelName, metadata);

            // Merge validation attributes
            input.MergeAttributes(validationAttributes);

            //contentBuilder.AppendLine(input.ToString());
            comboDate.AppendChild(input);

            // Declare date property selector
            Expression <Func <TModel, Int32> > datePropertySelector;

            // Select day property of date
            MemberExpression dayExpression = Expression.Property(expression.Body, "Day");

            datePropertySelector = Expression.Lambda <Func <TModel, Int32> >(
                dayExpression,
                expression.Parameters);

            // Create drop down button for day
            MvcHtmlString daySelector = htmlHelper
                                        .DropDownButtonFor <TModel, int>(
                datePropertySelector,
                new SelectList(Enumerable
                               .Range(1, 31)
                               .Select(m => new SelectListItem
            {
                Text  = m.ToString("00"),
                Value = m.ToString()
            })),
                dayText);

            // Setup day container
            FluentTagBuilder dayContainer = new FluentTagBuilder("div")
                                            .AddCssClass(dayContainerCss)
                                            .AppendChild(daySelector);

            //contentBuilder.AppendLine(dayContainer.ToString());

            comboDate.AppendChild(dayContainer);

            // Select month property of date
            MemberExpression monthExpression = Expression.Property(expression.Body, "Month");

            datePropertySelector = Expression.Lambda <Func <TModel, Int32> >(
                monthExpression,
                expression.Parameters);

            // Create drop down button for month
            MvcHtmlString monthSelector = htmlHelper
                                          .DropDownButtonFor <TModel, int>(
                datePropertySelector,
                new SelectList(Enumerable.Range(1, 12)
                               .Select(r => new SelectListItem
            {
                Value = r.ToString(),
                Text  = DateTimeFormatInfo.CurrentInfo.GetMonthName(r)
            })),
                monthText);

            // Setup month container
            FluentTagBuilder monthContainer = new FluentTagBuilder("div")
                                              .AddCssClass(monthContainerCss)
                                              .AppendChild(monthSelector);

            //contentBuilder.AppendLine(monthContainer.ToString());

            comboDate.AppendChild(monthContainer);

            // Select year property of date
            MemberExpression yearExpression = Expression.Property(expression.Body, "Year");

            datePropertySelector = Expression.Lambda <Func <TModel, Int32> >(
                yearExpression,
                expression.Parameters);

            // Create drop down button for month
            MvcHtmlString yearSelector = htmlHelper
                                         .DropDownButtonFor <TModel, int>(
                datePropertySelector,
                new SelectList(yearRange
                               .Select(r => new SelectListItem
            {
                Text  = r.ToString(),
                Value = r.ToString()
            })),
                yearText);

            // Setup year container
            FluentTagBuilder yearContainer = new FluentTagBuilder("div")
                                             .AddCssClass(yearContainerCss)
                                             .AppendChild(yearSelector);

            comboDate.AppendChild(yearContainer);

            // Set up error span
            MvcHtmlString validationMessage = htmlHelper
                                              .ValidationMessageFor(expression);

            FluentTagBuilder errorSpan = new FluentTagBuilder("span")
                                         .AddCssClass(errorCss)
                                         .AppendChild(validationMessage);

            comboDate.AppendChild(errorSpan);

            return(new MvcHtmlString(comboDate.Render()));
        }
Пример #50
0
 public static string PageHeader(this HtmlHelper helper, string title)
 {
     return(PageHeader(helper, title, null, null, null, null));
 }
Пример #51
0
        // ********************************************
        // TextBox - CPF
        // ********************************************
        public static HtmlString DnaMaisTextBoxCPF(this HtmlHelper htmlHelper, string display, string name, string value, int width, bool disabled)
        {
            var label = new TagBuilder("label");

            label.Attributes["class"] = "col-md-2 control-label";
            label.Attributes["for"]   = name;
            label.InnerHtml           = (display ?? name);

            var controle = new TagBuilder("div");

            controle.Attributes["class"] = "";

            var input = new TagBuilder("input");

            input.Attributes["type"]      = "text";
            input.Attributes["id"]        = name;
            input.Attributes["name"]      = name;
            input.Attributes["class"]     = "form-control";
            input.Attributes["maxlength"] = "14";
            input.Attributes["value"]     = value == null ? string.Empty : value.FormatarCPF();
            input.Attributes["style"]     = "width:" + width.ToString() + "px;";

            if (disabled)
            {
                input.Attributes["disabled"] = "disabled";
            }

            input.Attributes["onkeypress"] = "return onlyNumbers(event)";
            input.Attributes["onkeyup"]    = "maskCPF(this, event)";

            controle.InnerHtml = input.ToString();

            var div = new TagBuilder("div");

            div.Attributes["class"] = "form-group";
            div.InnerHtml           = label.ToString() + controle.ToString();



            ////var superDiv = new TagBuilder("div");

            //var label = new TagBuilder("label");
            //label.Attributes["class"] = "col-md-2 control-label";
            //label.Attributes["for"] = name;
            //label.InnerHtml = (display ?? name);

            //var controle = new TagBuilder("div");
            //controle.Attributes["class"] = "";

            //var input = new TagBuilder("input");
            //input.Attributes["type"] = "text";
            //input.Attributes["id"] = name;
            //input.Attributes["name"] = name;
            //input.Attributes["maxlength"] = "14";
            //input.Attributes["class"] = "form-control";
            //input.Attributes["value"] = value == null ? string.Empty : value.FormatarCPF();
            //input.Attributes["style"] = "width:" + width.ToString() + "px;";
            //if (disabled)
            //{
            //    input.Attributes["disabled"] = "disabled";
            //}
            //input.Attributes["onkeypress"] = "return onlyNumbers(event)";
            //input.Attributes["onkeyup"] = "maskCPF(this)";

            //controle.InnerHtml = input.ToString();

            //var div = new TagBuilder("div");
            //div.Attributes["class"] = "control-group";
            //div.InnerHtml = label.ToString() + controle.ToString();

            //superDiv.InnerHtml = div.ToString();

            return(new HtmlString(div.ToString()));
        }
Пример #52
0
        public virtual string RenderPartial(string pageName, object model, bool renderHtml, StreamWriter writer, HtmlHelper htmlHelper)
        {
            var httpReq   = htmlHelper.HttpRequest;
            var razorPage = this.viewManager.GetPageByName(pageName, httpReq, model);

            if (razorPage != null)
            {
                var page = CreateRazorPageInstance(httpReq, htmlHelper.HttpResponse, model, razorPage);
                page.ParentPage = htmlHelper.RazorPage;
                page.WriteTo(writer);
            }
            else
            {
                if (RenderPartialFn != null)
                {
                    RenderPartialFn(pageName, model, renderHtml, writer, htmlHelper, httpReq);
                }
                else
                {
                    writer.Write("<!--No RenderPartialFn, skipping {0}-->".Fmt(pageName));
                }
            }
            return(null);
        }
Пример #53
0
 /// <summary>
 /// 获取区域代码
 /// </summary>
 /// <param name="html"></param>
 /// <returns></returns>
 public static string CurrentCulture(this HtmlHelper html)
 {
     // split the ro-Ro string by '-' so it returns eg. ro / en
     return System.Threading.Thread.CurrentThread.CurrentCulture.Name.Split('-')[0];
 }
Пример #54
0
 /// <summary>
 /// Create combo date selector for date time.
 /// </summary>
 /// <exception cref="ArgumentNullException">
 /// When expression is null.
 /// </exception>
 /// <typeparam name="TModel">Type of model.</typeparam>
 /// <param name="htmlHelper">HtmlHelper.</param>
 /// <param name="expression">Property selector expression.</param>
 /// <returns>Combo date selector.</returns>
 public static MvcHtmlString ComboDateFor <TModel>(
     this HtmlHelper <TModel> htmlHelper,
     Expression <Func <TModel, DateTime> > expression)
 {
     return(htmlHelper.ComboDateFor(expression, null, null));
 }
Пример #55
0
 public TabComponent(HtmlHelper helper, string TabComponentId)
     : base(helper)
 {
     this._tabComponentId = TabComponentId;
     this._htmlHelper     = helper;
 }
        // Dynamic field errors based on entity + column

        public static string DynamicFieldErrors(this HtmlHelper html, object entity, MetaColumn column)
        {
            return(DynamicFieldErrors(html, entity, column.Name));
        }
Пример #57
0
        public static IHtmlString PermissionResource(this HtmlHelper htmlHelper, string key)
        {
            string resourceClass = "Permissions";

            return(htmlHelper.Resource(resourceClass, key));
        }
Пример #58
0
 public static TabComponent TabComponent(this HtmlHelper Html, string TabComponentId)
 {
     return(new TabComponent(Html, TabComponentId));
 }
Пример #59
0
    private static string GetContent <TModel, TProperty>(HtmlHelper <TModel> htmlHelper, Expression <Func <TModel, TProperty> > expression)
    {
        Func <TModel, TProperty> func = expression.Compile();

        return(func(htmlHelper.ViewData.Model).ToString());
    }
Пример #60
0
        public static IHtmlString Resource(this HtmlHelper htmlHelper, string resourceClass, string key)
        {
            string value = (string)HttpContext.GetGlobalResourceObject(resourceClass, key);

            return(MvcHtmlString.Create(value));
        }