public AuctionItemDetailModel(AuctionItem auctionItem) { Id = auctionItem.Id; AuctionNumber = auctionItem.AuctionNumber; Title = auctionItem.Title; Description = new MvcHtmlString(auctionItem.Description.Replace(Environment.NewLine, "<br/>")); MinimumPrice = auctionItem.MinimumPrice; Ended = auctionItem.Ended; ImageFileAttachments = new List<int>(); foreach (var fileAttachmentAuctionItem in FileAttachmentAuctionItemRepository.Instance.ListByAuctionItem(auctionItem.Id)) { ImageFileAttachments.Add(fileAttachmentAuctionItem.FileAttachmentId); } Biddings = new List<AuctionItemBiddingModel>(); AuctionItemBiddingRepository.Instance.ListByAuctionItem(auctionItem.Id).ForEach(b => Biddings.Add(new AuctionItemBiddingModel(b))); ImageFileAttachment = 0; if (ImageFileAttachments.Count > 0) { ImageFileAttachment = ImageFileAttachments[0]; } }
public static HtmlString WrapedInLabel(this HtmlHelper helper, MvcHtmlString @object, object labelAttribtues = null, object wrappedObjectAttribtues = null) { StringBuilder sb = new StringBuilder(); StringBuilder wrappedObjectSb = new StringBuilder(); Match match = Regex.Match(@object.ToHtmlString(), @"id=""(?<ID>\w+)"""); if (match.Success) { sb.AppendFormat("<label "); if (labelAttribtues != null) { PropertyInfo[] propertyInfos = labelAttribtues.GetType().GetProperties(); foreach (PropertyInfo propertyInfo in propertyInfos) { sb.AppendFormat(@"{0}=""{1}"">", propertyInfo.Name, propertyInfo.GetValue(labelAttribtues, null)); } } sb.AppendFormat(@"<strong>{0}</strong>", match.Groups["ID"].Value); wrappedObjectSb.Append(@object.ToHtmlString()); int firstWhiteSpace = @object.ToHtmlString().IndexOf(" "); if (wrappedObjectAttribtues != null) { PropertyInfo[] propertyInfos = wrappedObjectAttribtues.GetType().GetProperties(); foreach (PropertyInfo propertyInfo in propertyInfos) { wrappedObjectSb.Insert(firstWhiteSpace,String.Format(@" {0}=""{1}"" ", propertyInfo.Name, propertyInfo.GetValue(wrappedObjectAttribtues, null))); } } sb.AppendFormat("{0}", wrappedObjectSb); sb.Append("</label>"); } return new HtmlString(sb.ToString()); }
public Line Add(MvcHtmlString label, MvcHtmlString input, bool show = true) { string html = "{0}<div class='controls controls-row'>{1}</div>"; string lbl; if (show) { if (MvcHtmlString.IsNullOrEmpty(label)) { lbl = "<label class='control-label'> </label>"; } else { lbl = label.ToString().Replace("<label ", "<label class='control-label' "); } html = string.Format(html, lbl, input.ToString()); //TagBuilder l = new TagBuilder("div"); //l.AddCssClass("control-group"); //l.InnerHtml += MvcHtmlString.IsNullOrEmpty(label) ? "<label> </label>" : label.ToString(); //l.InnerHtml += input.ToString(); p.InnerHtml += html; } return this; }
public static MvcHtmlString RenderTemplates(this HtmlHelper helper, string virtualPath) { var absolutePath = HttpContext.Current.Request.MapPath(virtualPath); var cacheKey = string.Format(CACHE_KEY, "Templates", absolutePath); if (HttpRuntime.Cache[absolutePath] == null) { lock (_templatesLock) { if (HttpRuntime.Cache[absolutePath] == null) { var directoryInfo = new DirectoryInfo(absolutePath); if (directoryInfo.Exists) { var dependencyList = new List<string>(); var depth = 0; var templateContent = new MvcHtmlString(GetDirectoryTemplatesRecursive(directoryInfo, ref depth, dependencyList)); HttpRuntime.Cache.Insert(absolutePath, templateContent, new CacheDependency(dependencyList.ToArray())); } else { throw new Exception(string.Format("The template folder '{0}' could not be found.", absolutePath)); } } } } return HttpRuntime.Cache[absolutePath] as MvcHtmlString; }
public static MvcHtmlString RenderTextWithGuid(this HtmlHelper helper, string guid) { var path = GetPathToResource(helper.ViewContext); var items = DtoHelper.ToTextItemModel(path); var mvcString = new MvcHtmlString(items.First(x => x.Guid == guid).Text); return mvcString; }
public static MvcHtmlString Copyright( this HtmlHelper htmlHelper, string text) { MvcHtmlString result = new MvcHtmlString("Copyright " + DateTime.Now.Year + " " + text); return result; }
public static IHtmlString InputActionLink(this AjaxHelper ajaxHelper, ActionResult result, AjaxOptions ajaxOptions) { var builder = new TagBuilder("input"); var link = ajaxHelper.ActionLink("[replaceme]", result, ajaxOptions); var mvcLink = new MvcHtmlString(link.ToHtmlString().Replace("[replaceme]", builder.ToString(TagRenderMode.SelfClosing))); return mvcLink; }
public List<Breadcrumb> BuildBreadcrumbs(RequestContext context) { var result = new List<Breadcrumb>(); var html = GetHtmlHelper(context); var breadcrumbs = BuildTree(context); for (int i = 0; i < breadcrumbs.Count; i++) { var data = breadcrumbs[i].Data; if (!data.IsVisible) { break; } MvcHtmlString link = null; if (data.IsClickable) { if (i == 0) { link = new MvcHtmlString(string.Format("<a href='/'>{0}</a>", data.Title)); } else { var routeValues = data.RouteValues; foreach (string key in data.QueryString.Keys) { routeValues[key] = data.QueryString[key]; } link = html.ActionLink(data.Title, data.Action, data.Controller, routeValues, null); } } data.QueryString.Clear(); data.RouteValues.Clear(); result.Add(new Breadcrumb { Name = data.Title, IsDynamic = breadcrumbs[i].IsDynamic, Url = link }); } return result; }
/// <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; }
/// <summary> /// 输出Alter /// </summary> /// <param name="msg"></param> /// <returns></returns> protected virtual void Alter(string msg) { var str = new StringBuilder("<script type=\"text/javascript\">"); str.AppendFormat("alert('{0}');",msg); str.Append("</script>"); TempData["alter"] = new MvcHtmlString(str.ToString()); }
public static MvcHtmlString BootstrapTextbox(this HtmlHelper htmlHelper, MvcHtmlString htmlTextBox, string prepend, string append) { TagBuilder builder = new TagBuilder("div"); if (!string.IsNullOrEmpty(prepend)) { builder.AddCssClass("input-prepend"); TagBuilder span = new TagBuilder("span"); span.AddCssClass("add-on"); span.InnerHtml += prepend; builder.InnerHtml += span; } builder.InnerHtml += htmlTextBox; if (!string.IsNullOrEmpty(append)) { builder.AddCssClass("input-append"); TagBuilder span = new TagBuilder("span"); span.AddCssClass("add-on"); span.InnerHtml += append; builder.InnerHtml += span; } return MvcHtmlString.Create(builder.ToString()); }
protected void AppendMvcHtmlString(MvcHtmlString htmlString) { if (htmlString != null) { this.htmlTextWriter.Write(htmlString.ToString()); } }
public List<Breadcrumb> BuildBreadcrumbs(RequestContext context) { var result = new List<Breadcrumb>(); var html = GetHtmlHelper(context); var breadcrumbs = BuildTree(context); for (int i = 0; i < breadcrumbs.Count; i++) { var data = breadcrumbs[i].Data; MvcHtmlString link; if (i == 0) { link = new MvcHtmlString("<a href='" + new UrlHelper(context).Content("~/") + "'>" + data.Title + "</a>"); } else { var routeValues = data.RouteValues; foreach (string key in data.QueryString.Keys) { routeValues[key] = data.QueryString[key]; } link = html.ActionLink(data.Title, data.Action, data.Controller, routeValues, null); } data.QueryString.Clear(); data.RouteValues.Clear(); result.Add(new Breadcrumb { Name = data.Title, IsDynamic = breadcrumbs[i].IsDynamic, Url = link }); } return result; }
public IHtmlString Transform(HtmlHelper htmlHelper, INode node, string html) { var formHtml = html; var liContainingForm = new MvcHtmlString("<li>" + formHtml + "</li>"); var dropdownLinksButton = BootstrapHelper.DropdownLinksButton(node.DisplayName, liContainingForm); return dropdownLinksButton; }
public static string Resolve(MvcHtmlString content, int characters = 500) { string stripped; resolve(content, characters, out stripped); return stripped; }
public static bool IsNullOrEmpty(MvcHtmlString value) { if (value != null) return value._value.Length == 0; else return true; }
public static MvcHtmlString ImageLink( this HtmlHelper Helper, string ActionName, string ControllerName, object RouteValues, object LinkAttributes, string ImageSrc, string ImageAlt, object ImageAttributes) { TagBuilder imgTag = new TagBuilder("img"); imgTag.Attributes.Add("src", Helper.Encode(ImageSrc)); imgTag.Attributes.Add("alt", Helper.Encode(ImageAlt)); imgTag.MergeAttributes((IDictionary<string, object>)ImageAttributes, true); UrlHelper urlHelper = ((Controller)Helper.ViewContext.Controller).Url; var url = urlHelper.Action(ActionName, ControllerName, RouteValues); TagBuilder linkTag = new TagBuilder("a"); linkTag.MergeAttribute("href", url); linkTag.InnerHtml = imgTag.ToString(TagRenderMode.SelfClosing); linkTag.MergeAttributes((IDictionary<string, object>)LinkAttributes, true); MvcHtmlString html = new MvcHtmlString(linkTag.ToString()); return html; }
public TreePickerRenderModel() { Id = Name = new MvcHtmlString("gen_" + Guid.NewGuid().ToString("N")); ChooseLinkText = "Choose..."; DeleteLinkText = "Delete"; ModalTitle = "Choose item"; StartNodeId = HiveId.Empty; }
public static IHtmlString InputActionLink(this AjaxHelper ajaxHelper, ActionResult result, AjaxOptions ajaxOptions, object htmlAttributes) { var builder = new TagBuilder("input"); builder.MergeAttributes(new RouteValueDictionary(htmlAttributes)); var link = ajaxHelper.ActionLink("[replaceme]", result, ajaxOptions); var mvcLink = new MvcHtmlString(link.ToHtmlString().Replace("[replaceme]", builder.ToString(TagRenderMode.SelfClosing))); return mvcLink; }
/// <summary> /// Generate a image tag inside a link tag /// </summary> public static MvcHtmlString ImageLink(this HtmlHelper helper, string href, MvcHtmlString htmlImage, object htmlAttributes = null) { var tag = new TagBuilder("a"); tag.MergeAttribute("href", GetContentPath(href), true); tag.MergeAttributes(new RouteValueDictionary(htmlAttributes)); tag.InnerHtml += htmlImage; return MvcHtmlString.Create(tag.ToString(TagRenderMode.Normal)); }
public static MvcHtmlString TimedRedirectToUrl(this HtmlHelper h, long seconds, string action, string controller) { var urlHelper = new UrlHelper(h.ViewContext.RequestContext); var url = urlHelper.Action(controller, action); //<META HTTP-EQUIV="Refresh" CONTENT="3000;URL=/Index/Home; var outp = new MvcHtmlString("<META HTTP-EQUIV=\"Refresh\" CONTENT=\"" + seconds + ";URL=\"" + url+"\">"); return outp; }
public static MvcHtmlString GetMenu(this HtmlHelper hlp) { if (DateTime.Now - TimeCashe > PeriodCache) { TimeCashe = DateTime.Now; Cashe = MvcHtmlString.Create(GetMenuCats() + GetMenuPosts()); } return Cashe; }
public static MvcHtmlString GetAnchor(this HtmlHelper target, string linkText, string targetUrl) { string temp= string.Format("<a href=\"{0}\">{1}</a>",targetUrl,linkText); MvcHtmlString returnValue = new MvcHtmlString(temp); return returnValue; }
public FormRow AddToRight(MvcHtmlString markup) { if (markup != null) { return AddToRight(markup.ToString()); } return this; }
public static string ResolveWithTrailling(MvcHtmlString content, int characters = 500) { string stripped; if (resolve(content, characters, out stripped)) { return "{0}...".FormatWith(stripped); } return stripped; }
public static MvcHtmlString MenuItem(this HtmlHelper helper, MvcHtmlString link, string controller) { var li = new TagBuilder("li"); if (helper.ViewContext.Controller.GetType().Name.ToLower() == String.Format("{0}controller", controller).ToLower()) li.Attributes.Add("class", "selected"); li.InnerHtml = link.ToHtmlString(); return new MvcHtmlString(li.ToString()); }
public static MvcHtmlString ActionLink(this HtmlHelper htmlHelper, string linkText, string actionName, string controllerName, string roles, MatchType RoleMatchType, object route) { bool valid = UserFunctions.IsUserInRole(roles, RoleMatchType); var link = new MvcHtmlString(string.Empty); if (valid) { link = htmlHelper.ActionLink(linkText, actionName, controllerName, route,null); } return link; }
/// <summary> /// Successes the specified message. /// </summary> /// <param name="message">The message.</param> /// <returns>MvcHtmlString.</returns> public static MvcHtmlString Success(this string message) { var msg = new MvcHtmlString(string.Empty); if (!string.IsNullOrEmpty(message)) { msg = new MvcHtmlString(string.Format("<p style=\"margin-top:15px;\" class=\"text-success\" >{0}<p>", message)); } return msg; }
public ActionResult Delete(int id, IDeleteService service) { var response = service.Delete<Tag>(id); if (response.IsValid) TempData["message"] = response.SuccessMessage; else //else errors, so send back an error message TempData["errorMessage"] = new MvcHtmlString(response.ErrorsAsHtml()); return RedirectToAction("Index"); }
/// <summary> /// Socials the share options. Redirect to the SocialShare control if exist else render error message /// </summary> /// <param name="helper">The HTML helper.</param> public static System.Web.Mvc.MvcHtmlString SocialShareOptions(this HtmlHelper helper) { System.Web.Mvc.MvcHtmlString result; try { result = helper.Action(ActionName, ControllerName); } catch (HttpException e) { result = new System.Web.Mvc.MvcHtmlString("The SocialShare widget could not be found."); } return(result); }
/// <summary> /// Socials the share options. Redirect to the SocialShare control if exist else render error message /// </summary> /// <param name="helper">The HTML helper.</param> /// <param name="dataItem">The data item which we will be sharing</param> public static System.Web.Mvc.MvcHtmlString SocialShareOptions(this HtmlHelper helper, Telerik.Sitefinity.Model.IHasTitle dataItem) { System.Web.Mvc.MvcHtmlString result; try { RouteValueDictionary routeValues = new RouteValueDictionary(); routeValues.Add(SocialShareHelpers.DataItemKey, dataItem); result = helper.Action(ActionName, ControllerName, routeValues); } catch (HttpException) { result = new System.Web.Mvc.MvcHtmlString("The SocialShare widget could not be found."); } return(result); }
public void RegisterScript_TwoTimes_NoDuplicateRegistrations() { var dummyHttpContext = new DummyHttpContext(); var dummyViewContext = new ViewContext(); dummyViewContext.HttpContext = dummyHttpContext; var dummyViewDataContainer = (IViewDataContainer) new ViewPage(); var script = "Mvc/Scripts/Designer/modal-dialog.js"; var htmlHelper = new System.Web.Mvc.HtmlHelper(dummyViewContext, dummyViewDataContainer); System.Web.Mvc.MvcHtmlString result = htmlHelper.Script(script); Assert.AreEqual(result.ToString(), string.Format(System.Globalization.CultureInfo.InvariantCulture, "<script src=\"{0}\" type=\"text/javascript\"></script>", script)); result = htmlHelper.Script(script); Assert.AreEqual(result, System.Web.Mvc.MvcHtmlString.Empty); }
public static System.Web.Mvc.MvcHtmlString SocialShareOptions(this HtmlHelper helper, Telerik.Sitefinity.Model.IHasTitle dataItem, string templateName) { System.Web.Mvc.MvcHtmlString result; try { // Default Implementation from https://github.com/Sitefinity/feather/blob/68eb70be27d7925299002930b364088db2703f31/Telerik.Sitefinity.Frontend/Mvc/Helpers/SocialShareHelpers.cs RouteValueDictionary routeValues = new RouteValueDictionary(); routeValues.Add(SocialShareOptionsHelper.DataItemKey, dataItem); // Add template name routeValues.Add(TemplateNameKey, templateName); result = helper.Action(ActionName, ControllerName, routeValues); } catch (HttpException) { result = new System.Web.Mvc.MvcHtmlString("The SocialShare widget could not be found."); } return(result); }
public static MvcHtmlString SideBarSecureActionLink(this HtmlHelper htmlHelper, string linkText, string url, string cssClass, string spanCssClass, params string[] permission) { var hasPermission = permission.Any(HttpContext.Current.User.IsInRole); if (!hasPermission) { return(MvcHtmlString.Empty); } var a = new TagBuilder("a"); a.Attributes.Add("href", url); a.AddCssClass(cssClass); var span = new TagBuilder("span"); span.AddCssClass(spanCssClass); a.InnerHtml = span.ToString(TagRenderMode.Normal) + linkText; return(MvcHtmlString.Create(a.ToString())); }
/// <summary> /// Registers resource reference. /// </summary> /// <param name="register">The register.</param> /// <param name="resourceKey">The resource key.</param> /// <param name="throwException">if set to <c>true</c> [throw exception].</param> /// <param name="tagName">Name of the tag.</param> /// <param name="attribbutes">The attribbutes.</param> /// <returns></returns> private static System.Web.Mvc.MvcHtmlString RegisterResource(ResourceRegister register, string resourceKey, bool throwException, string tagName, KeyValuePair <string, string>[] attribbutes) { string output; System.Web.Mvc.MvcHtmlString result; if (throwException) { register.RegisterResource(resourceKey); output = ResourceHelper.GenerateTag(tagName, attribbutes); result = new System.Web.Mvc.MvcHtmlString(output); } else if (register.TryRegisterResource(resourceKey)) { output = ResourceHelper.GenerateTag(tagName, attribbutes); result = new System.Web.Mvc.MvcHtmlString(output); } else { result = System.Web.Mvc.MvcHtmlString.Empty; } return(result); }
/// <summary> /// Outputs simple call to function that updates CKEditors before client-side validators are called. /// </summary> /// <example>Razor View: <input type="text" value="submit" onclick="@Html.CKEditorSubmitButtonUpdateFunction()"/></example> /// <returns>MvcHtmlString literal: javascript:UpdateCKEditors()</returns> public static MvcHtmlString CKEditorSubmitButtonUpdateFunction(this HtmlHelper help) { return(MvcHtmlString.Create("javascript:UpdateCKEditors()")); }
private static MvcHtmlString CKEditorHelper(HtmlHelper htmlHelper, ModelMetadata modelMetadata, string name, IDictionary <string, object> rowsAndColumns, IDictionary <string, object> htmlAttributes, string ckEditorConfigOptions) { string fullName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(name); if (String.IsNullOrEmpty(fullName)) { throw new ArgumentException("string parameter is null or empty", "name"); } TagBuilder textAreaBuilder = new TagBuilder("textarea"); textAreaBuilder.GenerateId(fullName); textAreaBuilder.MergeAttributes(htmlAttributes, true); textAreaBuilder.MergeAttribute("name", fullName, true); string style = ""; if (textAreaBuilder.Attributes.ContainsKey("style")) { style = textAreaBuilder.Attributes["style"]; } if (string.IsNullOrWhiteSpace(style)) { style = ""; } style += string.Format("height:{0}em; width:{1}em;", rowsAndColumns["rows"], rowsAndColumns["cols"]); textAreaBuilder.MergeAttribute("style", style, true); // If there are any errors for a named field, we add the CSS attribute. ModelState modelState; if (htmlHelper.ViewData.ModelState.TryGetValue(fullName, out modelState) && modelState.Errors.Count > 0) { textAreaBuilder.AddCssClass(HtmlHelper.ValidationInputCssClassName); } textAreaBuilder.MergeAttributes(htmlHelper.GetUnobtrusiveValidationAttributes(name)); string value; if (modelState != null && modelState.Value != null) { value = modelState.Value.AttemptedValue; } else if (modelMetadata.Model != null) { value = modelMetadata.Model.ToString(); } else { value = String.Empty; } // The first newline is always trimmed when a TextArea is rendered, so we add an extra one // in case the value being rendered is something like "\r\nHello". textAreaBuilder.SetInnerText(Environment.NewLine + value); TagBuilder scriptBuilder = new TagBuilder("script"); scriptBuilder.MergeAttribute("type", "text/javascript"); if (string.IsNullOrEmpty(ckEditorConfigOptions)) { ckEditorConfigOptions = string.Format("{{ width:'{0}em', height:'{1}em', CKEDITOR.config.allowedContent : true }}", rowsAndColumns["cols"], rowsAndColumns["rows"]); } if (!ckEditorConfigOptions.Trim().StartsWith("{")) { ckEditorConfigOptions = "{" + ckEditorConfigOptions; } if (!ckEditorConfigOptions.Trim().EndsWith("}")) { ckEditorConfigOptions += "}"; } scriptBuilder.InnerHtml = string.Format(" $('#{0}').ckeditor({1}).addClass('{2}'); ", fullName, ckEditorConfigOptions, CK_Ed_Class ); return(MvcHtmlString.Create(textAreaBuilder.ToString() + "\n" + scriptBuilder.ToString())); }
/// <summary> /// Produces HTML to insert scripts needed to insert CKEditor instances. To be used once per page, toward the top of a view. /// </summary> public static MvcHtmlString CKEditorHeaderScripts(this HtmlHelper help) { return(MvcHtmlString.Create(@"<script src=""" + CK_Ed_Location + @"ckeditor.js"" type=""text/javascript""></script> <script src=""" + CK_Ed_Location + @"adapters/jquery.js"" type=""text/javascript""></script> <script type=""text/javascript""> function UpdateCKEditors() { $('." + CK_Ed_Class + @"').ckeditorGet().updateElement(); } </script>")); }
public static MvcHtmlString InsertFileContentCached(this HtmlHelper helper, [PathReference] string path, int duration = 0) { var result = new MvcHtmlString(string.Empty); try { if (Convert.ToBoolean(ConfigurationManager.AppSettings["IgnoreCacheForInsertFileContentCached"])) { return InsertFileContent(helper, path); } var cacheKey = "insertFile|" + path.GetHashCode(); var cached = HttpRuntime.Cache.Get(cacheKey) as MvcHtmlString; if (cached != null) { return cached; } result = InsertFileContent(helper, path); HttpRuntime.Cache.Add(cacheKey, result, null /*dependencies*/, Cache.NoAbsoluteExpiration, duration == 0 ? Cache.NoSlidingExpiration : TimeSpan.FromSeconds(duration), CacheItemPriority.Normal, null /*onRemoveCallback*/); } catch (Exception ex) { result = new MvcHtmlString("Exception occured at " + path + " details: " + ex.Message); } return result; }