public static MvcHtmlString ViewsOnOff <M>(this HtmlHelper <M> htmlHelper, string groupName, bool initialOn) { if (groupName == null) { throw (new ArgumentNullException("groupName")); } string viewsOnOffScript = null; string partialName = groupName + "_selection"; string fullName = htmlHelper.ViewData.TemplateInfo.GetFullHtmlFieldName(partialName); string fullId = BasicHtmlHelper.IdFromName(fullName); switch (MvcEnvironment.Validation(htmlHelper)) { case ValidationType.StandardClient: viewsOnOffScript = viewsOnOfScriptStandardClient; break; case ValidationType.UnobtrusiveClient: viewsOnOffScript = viewsOnOfScriptScriptUnobtrusiveClient; break; default: viewsOnOffScript = viewsOnOfScriptScriptNoClient; break; } ValueProviderResult vr = htmlHelper.ViewContext.Controller.ValueProvider.GetValue(fullName); if (vr != null) { initialOn = (bool)(vr.ConvertTo(typeof(bool))); } return(MvcHtmlString.Create( htmlHelper.Hidden(partialName, initialOn) + string.Format(viewsOnOffScript, groupName, initialOn ? "true":"false", fullId) )); }
public static MvcHtmlString ViewList <M>( this HtmlHelper <M> htmlHelper, string groupName, string cssSelected, string selection = null) { if (groupName == null) { throw (new ArgumentNullException("groupName")); } string partialName = groupName + "_selection"; string fullId = BasicHtmlHelper.IdFromName(htmlHelper.ViewData.TemplateInfo.GetFullHtmlFieldName(partialName)); string viewSelectionScript = null; switch (MvcEnvironment.Validation(htmlHelper)) { case ValidationType.StandardClient: viewSelectionScript = viewSelectionScriptStandardClient; break; case ValidationType.UnobtrusiveClient: viewSelectionScript = viewSelectionScriptUnobtrusiveClient; break; default: viewSelectionScript = viewSelectionScriptNoClient; break; } if (string.IsNullOrWhiteSpace(selection)) { selection = string.Empty; } string prefix = htmlHelper.ViewData.TemplateInfo.HtmlFieldPrefix; if (string.IsNullOrWhiteSpace(prefix)) { prefix = string.Empty; } else { prefix = BasicHtmlHelper.IdFromName(prefix) + "_"; } ValueProviderResult vr = htmlHelper.ViewContext.Controller.ValueProvider.GetValue(htmlHelper.ViewData.TemplateInfo.GetFullHtmlFieldName(partialName)); if (vr != null) { string oldres = vr.ConvertTo(typeof(string)) as string; if (!string.IsNullOrWhiteSpace(oldres)) { selection = oldres; } } if (string.IsNullOrWhiteSpace(cssSelected)) { cssSelected = string.Empty; } return (MvcHtmlString.Create( htmlHelper.Hidden(partialName, selection) + string.Format(viewSelectionScript, groupName, fullId, selection, cssSelected, prefix))); }
public static MvcHtmlString ViewListFor <M>( this HtmlHelper <M> htmlHelper, Expression <Func <M, string> > expression, string groupName, string cssSelected) { if (expression == null) { throw (new ArgumentNullException("expression")); } if (groupName == null) { throw (new ArgumentNullException("groupName")); } string viewSelectionScript = null; switch (MvcEnvironment.Validation(htmlHelper)) { case ValidationType.StandardClient: viewSelectionScript = viewSelectionScriptStandardClient; break; case ValidationType.UnobtrusiveClient: viewSelectionScript = viewSelectionScriptUnobtrusiveClient; break; default: viewSelectionScript = viewSelectionScriptNoClient; break; } string partialName = ExpressionHelper.GetExpressionText(expression); string fullId = BasicHtmlHelper.IdFromName(htmlHelper.ViewData.TemplateInfo.GetFullHtmlFieldName(partialName)); string selection = string.Empty; try { selection = expression.Compile().Invoke(htmlHelper.ViewData.Model) as string; } catch { } string prefix = htmlHelper.ViewData.TemplateInfo.HtmlFieldPrefix; if (string.IsNullOrWhiteSpace(prefix)) { prefix = string.Empty; } else { prefix = BasicHtmlHelper.IdFromName(prefix) + "_"; } if (string.IsNullOrWhiteSpace(cssSelected)) { cssSelected = string.Empty; } return (MvcHtmlString.Create( htmlHelper.Hidden(partialName, selection) + string.Format(viewSelectionScript, groupName, fullId, selection, cssSelected, prefix))); }
public static MvcHtmlString TreeViewToggleEditButtonFor <VM, T>( this HtmlHelper <VM> htmlHelper, Expression <Func <VM, IEnumerable <T> > > expression, string textOrUrlEdit, string cssClassEdit, string textOrUrlUndoEdit, string cssClassUndoEdit, string textOrUrlRedoEdit, string cssClassRedoEdit, ManipulationButtonStyle manipulationButtonStyle = ManipulationButtonStyle.Button) { if (expression == null) { throw (new ArgumentNullException("expression")); } if (textOrUrlEdit == null) { throw (new ArgumentNullException("textOrUrlEdit")); } if (cssClassEdit == null) { throw (new ArgumentNullException("cssClassEdit")); } if (textOrUrlUndoEdit == null) { throw (new ArgumentNullException("textOrUrlUndoEdit")); } if (cssClassUndoEdit == null) { throw (new ArgumentNullException("cssClassUndoEdit")); } if (textOrUrlRedoEdit == null) { throw (new ArgumentNullException("textOrUrlRedoEdit")); } if (cssClassRedoEdit == null) { throw (new ArgumentNullException("cssClassRedoEdit")); } if (MvcEnvironment.Validation(htmlHelper) == ValidationType.StandardClient) { return(MvcHtmlString.Create(string.Empty)); } string id = BasicHtmlHelper.IdFromName(htmlHelper.ViewData.TemplateInfo.GetFullHtmlFieldName(ExpressionHelper.GetExpressionText(expression))); return(MvcHtmlString.Create( string.Format(initializeToggleEditButtonScript, id, textOrUrlEdit, cssClassEdit, textOrUrlUndoEdit, cssClassUndoEdit, textOrUrlRedoEdit, cssClassRedoEdit) + htmlHelper.ManipulationButton(ManipulationButtonType.Custom, string.Empty, string.Format(toggleEditButtonScript, id, textOrUrlEdit, cssClassEdit, textOrUrlUndoEdit, cssClassUndoEdit, textOrUrlRedoEdit, cssClassRedoEdit), id + "_ToggleEditButton", manipulationButtonStyle, null).ToString())); }
private void EndCapturingValidation(ViewContext viewContext) { switch (MvcEnvironment.Validation(viewContext)) { case ValidationType.StandardClient: viewContext.OutputClientValidation(); break; case ValidationType.UnobtrusiveClient: break; default: break; } viewContext.ClientValidationEnabled = oldClientSetting; }
public void SetHelper(HtmlHelper htmlHelper) { if (this.htmlHelper != htmlHelper) { this.htmlHelper = htmlHelper; switch (MvcEnvironment.Validation(htmlHelper)) { case MVCControlsToolkit.Core.ValidationType.StandardClient: validationType = "StandardClient"; break; case MVCControlsToolkit.Core.ValidationType.UnobtrusiveClient: validationType = "UnobtrusiveClient"; break; default: validationType = "Server"; break; } } }
public static IBindingsBuilder <T> ItemClientViewModel <T>( this HtmlHelper <T> htmlHelper ) where T : class, new() { string validationType = null; switch (MvcEnvironment.Validation(htmlHelper)) { case ValidationType.StandardClient: validationType = "StandardClient"; break; case ValidationType.UnobtrusiveClient: validationType = "UnobtrusiveClient"; break; default: validationType = "Server"; break; } return(new BindingsBuilder <T>(htmlHelper.ViewContext.Writer, string.Empty, string.Empty, validationType, null, htmlHelper)); }
internal static MvcHtmlString MinMaxBase <VM>( this HtmlHelper <VM> htmlHelper, string type, string name, object value, ModelMetadata metaData = null, IDictionary <string, object> htmlAttributes = null) { string partialName = name; if (name == null) { throw new ArgumentNullException("name"); } name = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(name); TagBuilder tagBuilder = new TagBuilder("input"); tagBuilder.MergeAttributes(htmlAttributes); tagBuilder.MergeAttribute("name", name, true /* replaceExisting */); tagBuilder.MergeAttribute("type", type, true /* replaceExisting */); tagBuilder.MergeAttribute("value", Convert.ToString(value), true /* replaceExisting */); tagBuilder.GenerateId(name); ModelState modelState; if (htmlHelper.ViewData.ModelState.TryGetValue(name, out modelState)) { if (modelState.Errors.Count > 0) { tagBuilder.AddCssClass(HtmlHelper.ValidationInputCssClassName); } } IDictionary <String, object> validation = MvcEnvironment.GetUnobtrusiveValidation(htmlHelper, name, metaData); if (validation != null) { if (validation.ContainsKey("data-val-dynamicrange-min")) { tagBuilder.MergeAttribute("min", Convert.ToString(validation["data-val-dynamicrange-min"]), false); } if (validation.ContainsKey("data-val-dynamicrange-max")) { tagBuilder.MergeAttribute("max", Convert.ToString(validation["data-val-dynamicrange-max"]), false); } } return(MvcHtmlString.Create(tagBuilder.ToString())); }
public static MvcHtmlString TreeViewAddButton <VM>( this HtmlHelper <VM> htmlHelper, int templateToUse, string textOrUrl, ManipulationButtonStyle manipulationButtonStyle = ManipulationButtonStyle.Button, IDictionary <string, object> htmlAttributes = null, string name = null) { if (MvcEnvironment.Validation(htmlHelper) == ValidationType.StandardClient) { return(MvcHtmlString.Create(string.Empty)); } string id = htmlHelper.PrefixedId("ItemsContainer"); return(htmlHelper.ManipulationButton(ManipulationButtonType.Custom, textOrUrl, string.Format(addButtonScript, id, templateToUse), name == null ? id + "_AddButton" + templateToUse.ToString() : name, manipulationButtonStyle, htmlAttributes)); }
public Pager(HtmlHelper <VM> htmlHelper, int currPage, int?totPages, string parameterName, string actionName, string targetIdName, string controllerName = null, object otherParameters = null, string routeName = null, string protocol = null, string hostname = null, string fragment = null) { this.currPage = currPage; this.totPages = totPages; this.fieldName = string.Empty; this.fieldPartialName = string.Empty; pageFieldRendered = false; this.htmlHelper = htmlHelper; this.controllerName = controllerName; this.actionName = actionName; this.parameterName = parameterName; this.targetIdName = targetIdName; this.protocol = protocol; this.hostname = hostname; this.fragment = fragment; this.routeName = routeName; this.otherParameters = otherParameters; if (string.IsNullOrWhiteSpace(controllerName)) { goTextName = "CurrentController_" + actionName + "_" + parameterName + "_gotext"; } else { goTextName = controllerName + "_" + actionName + "_" + parameterName + "_gotext"; } switch (MvcEnvironment.Validation(htmlHelper)) { case ValidationType.StandardClient: validationType = "StandardClient"; break; case ValidationType.UnobtrusiveClient: validationType = "UnobtrusiveClient"; break; default: validationType = "Server"; break; } }
public Pager(HtmlHelper <VM> htmlHelper, string fieldName, string prevFieldName, int currPage, int?prevPage, int?totPages, string fieldPartialName) { this.currPage = currPage; this.prevPage = prevPage; this.totPages = totPages; this.fieldName = fieldName; this.fieldPartialName = fieldPartialName; this.prevFieldName = prevFieldName; pageFieldRendered = false; this.htmlHelper = htmlHelper; this.targetIdName = string.Empty; goTextName = fieldPartialName + "_gotext"; switch (MvcEnvironment.Validation(htmlHelper)) { case ValidationType.StandardClient: validationType = "StandardClient"; break; case ValidationType.UnobtrusiveClient: validationType = "UnobtrusiveClient"; break; default: validationType = "Server"; break; } }
public ClientPager(HtmlHelper <VM> htmlHelper, string fieldName, int currPage, string totPagesFieldName, int?totPages, string pagePrefix, string pagePostfix, bool causeSubmit) { this.htmlHelper = htmlHelper; this.currPage = currPage; this.fieldName = fieldName; this.fieldId = BasicHtmlHelper.IdFromName(fieldName); this.totPages = totPages; this.totPagesFieldName = totPagesFieldName; this.pageFieldRendered = false; this.pagePrefix = pagePrefix; this.pagePostfix = pagePostfix; goTextName = fieldId + "_goto"; this.causeSubmit = causeSubmit; switch (MvcEnvironment.Validation(htmlHelper)) { case ValidationType.StandardClient: validationType = "StandardClient"; break; case ValidationType.UnobtrusiveClient: validationType = "UnobtrusiveClient"; break; default: validationType = "Server"; break; } }
public static MvcHtmlString SortableListAddButtonFor <VM, TItem>( this HtmlHelper <VM> htmlHelper, RenderInfo <IEnumerable <TItem> > renderInfo, string textOrUrl, ManipulationButtonStyle manipulationButtonStyle = ManipulationButtonStyle.Button, IDictionary <string, object> htmlAttributes = null, string name = null, int templateIndex = 0) { if (renderInfo == null) { throw (new ArgumentNullException("renderInfo")); } if (MvcEnvironment.Validation(htmlHelper) == ValidationType.StandardClient) { return(MvcHtmlString.Create(string.Empty)); } string id = BasicHtmlHelper.IdFromName(renderInfo.Prefix); return(htmlHelper.ManipulationButton(ManipulationButtonType.Custom, textOrUrl, string.Format(addButtonScript, id, templateIndex), name == null ? id + "_AddButton" + templateIndex.ToString(CultureInfo.InvariantCulture) : name, manipulationButtonStyle, htmlAttributes)); }
public static MvcHtmlString SortableListAddButtonFor <VM, T>( this HtmlHelper <VM> htmlHelper, Expression <Func <VM, IEnumerable <T> > > expression, string textOrUrl, ManipulationButtonStyle manipulationButtonStyle = ManipulationButtonStyle.Button, IDictionary <string, object> htmlAttributes = null, string name = null, int templateIndex = 0) { if (expression == null) { throw (new ArgumentNullException("expression")); } if (MvcEnvironment.Validation(htmlHelper) == ValidationType.StandardClient) { return(MvcHtmlString.Create(string.Empty)); } string id = BasicHtmlHelper.IdFromName(htmlHelper.ViewData.TemplateInfo.GetFullHtmlFieldName(ExpressionHelper.GetExpressionText(expression))); return(htmlHelper.ManipulationButton(ManipulationButtonType.Custom, textOrUrl, string.Format(addButtonScript, id, templateIndex), name == null ? id + "_AddButton" + templateIndex.ToString(CultureInfo.InvariantCulture) : name, manipulationButtonStyle, htmlAttributes)); }
public static MvcHtmlString SubmitTimer <VM>( this HtmlHelper <VM> htmlHelper, TimeSpan timeInterval, string clientViewModel = null) { if (clientViewModel != null) { return(MvcHtmlString.Create( string.Format(saveAndSubmitTimerScript, clientViewModel, timeInterval.TotalMilliseconds))); } string validationType = null; switch (MvcEnvironment.Validation(htmlHelper)) { case ValidationType.StandardClient: validationType = "StandardClient"; break; case ValidationType.UnobtrusiveClient: validationType = "UnobtrusiveClient"; break; default: validationType = "Server"; break; } string targetIdName = BasicHtmlHelper.GetUniqueSymbol(htmlHelper, submitSymbol); return(MvcHtmlString.Create( string.Format(submitTimerScript, validationType, targetIdName, timeInterval.TotalMilliseconds) )); }
public static MvcHtmlString ClientTemplate <T>(this HtmlHelper htmlHelper, string uniqueName, object template, bool?applyAutomaticBindings = null, T prototype = null) where T : class { if (string.IsNullOrWhiteSpace(uniqueName)) { throw new ArgumentNullException("uniqueName"); } if (template == null) { throw new ArgumentNullException("template"); } htmlHelper.ViewContext.HttpContext.Items["ClientTemplateOn"] = new object(); bool oldValidation = htmlHelper.ViewContext.ClientValidationEnabled; if (!MvcEnvironment.UnobtrusiveAjaxOn(htmlHelper)) { htmlHelper.ViewContext.ClientValidationEnabled = false; } FormContext oldFormContext = htmlHelper.ViewContext.FormContext; htmlHelper.ViewContext.FormContext = new FormContext(); string validationType = null; bool automaticBindings = false; if (applyAutomaticBindings.HasValue) { automaticBindings = applyAutomaticBindings.Value; } else { automaticBindings = htmlHelper.ViewData["ClientBindings"] != null; } switch (MvcEnvironment.Validation(htmlHelper)) { case ValidationType.StandardClient: validationType = "StandardClient"; break; case ValidationType.UnobtrusiveClient: validationType = "UnobtrusiveClient"; break; default: validationType = "Server"; break; } IBindingsBuilder <T> bindings = new BindingsBuilder <T>(htmlHelper.ViewContext.Writer, string.Empty, templateSymbol + "0.A", validationType, null, htmlHelper); string stringTemplate = new TemplateInvoker <T>(template, bindings).InvokeVirtual(htmlHelper, templateSymbol + "0.A"); if (automaticBindings) { stringTemplate = new KoAutomaticBinder <T>(stringTemplate, bindings).ToString(); } else { stringTemplate = new KoAutomaticBinder <T>(stringTemplate, null).ToString(); } /* stringTemplate = stringTemplate.Replace(templateSymbol + ".A", "${MvcControlsToolkit_TemplateName($item)}") * .Replace(templateSymbol + "_A", "${MvcControlsToolkit_TemplateId($item)}");*/ /* stringTemplate = stringTemplate.Replace(templateSymbol + ".A", templateSymbol+"0.A") * .Replace(templateSymbol + "_A", templateSymbol+"0_A"); */ string globalEvals = string.Empty; if (htmlHelper.ViewContext.HttpContext.Items.Contains("GlobalEvalsRequired")) { StringBuilder globalEvalsBuilder = htmlHelper.ViewContext.HttpContext.Items["GlobalEvalsRequired"] as StringBuilder; globalEvals = globalEvalsBuilder.ToString(); htmlHelper.ViewContext.HttpContext.Items.Remove("GlobalEvalsRequired"); } string prototypeDeclaration = string.Empty; if (prototype != null) { ModelTranslator <T> model = new ModelTranslator <T>(); model.ImportFromModel(prototype); prototypeDeclaration = string.Format(prototypeFormat, uniqueName, model.JSonModel); } MvcHtmlString res = MvcHtmlString.Create(string.Format(clientTemplateScript, uniqueName, stringTemplate, globalEvals, prototypeDeclaration )); htmlHelper.ViewContext.FormContext = oldFormContext; htmlHelper.ViewContext.ClientValidationEnabled = oldValidation; htmlHelper.ViewContext.HttpContext.Items.Remove("ClientTemplateOn"); return(res); }
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())); }
internal static MvcHtmlString DropDownbase <VM, TItem, TDisplay, TValue>( this HtmlHelper <VM> htmlHelper, string name, object value, List <ExtendedSelectListItem> items, IDictionary <string, object> htmlAttributes, bool allowsMultipleValues, bool useGroups, ModelMetadata metaData = null) { string partialName = name; if (name == null) { throw new ArgumentNullException("name"); } name = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(name); if (items == null) { throw new ArgumentNullException("items"); } object defaultValue = (allowsMultipleValues) ? htmlHelper.GetModelStateValue(name, typeof(string[])) : htmlHelper.GetModelStateValue(name, typeof(string)); if (defaultValue == null) { defaultValue = value; } if (defaultValue != null) { IEnumerable defaultValues = (allowsMultipleValues) ? defaultValue as IEnumerable : new[] { defaultValue }; IEnumerable <string> values = (from object currValue in defaultValues select Convert.ToString(currValue, CultureInfo.CurrentCulture)).ToList(); HashSet <string> selectedValues = new HashSet <string>(values, StringComparer.OrdinalIgnoreCase); foreach (ExtendedSelectListItem item in items) { item.Selected = (item.Value != null) ? selectedValues.Contains(item.Value) : selectedValues.Contains(item.Text); } } StringBuilder listItemBuilder = new StringBuilder(); if (useGroups) { foreach (var group in items.GroupBy(i => i.GroupKey)) { var groupProps = group.Select(it => new { Name = it.GroupName, Attrs = it.GroupAttributes }).FirstOrDefault(); IDictionary <string, object> dictionary = groupProps.Attrs as IDictionary <string, object>; if (group.Key != null && groupProps.Name != null) { if (dictionary != null) { listItemBuilder.AppendLine(string.Format("<optgroup label=\"{0}\" value=\"{1}\" {2}>", htmlHelper.Encode(groupProps.Name), htmlHelper.Encode(group.Key), BasicHtmlHelper.GetAttributesString(dictionary))); } else { listItemBuilder.AppendLine(string.Format("<optgroup label=\"{0}\" value=\"{1}\" {2}>", htmlHelper.Encode(groupProps.Name), htmlHelper.Encode(group.Key), BasicHtmlHelper.GetAttributesString(groupProps.Attrs))); } } foreach (ExtendedSelectListItem item in group) { listItemBuilder.AppendLine(ListItemToOption(item)); } if (group.Key != null && groupProps.Name != null) { listItemBuilder.AppendLine("</optgroup>"); } } } else { foreach (ExtendedSelectListItem item in items) { listItemBuilder.AppendLine(ListItemToOption(item)); } } TagBuilder tagBuilder = new TagBuilder("select") { InnerHtml = listItemBuilder.ToString() }; tagBuilder.MergeAttributes(htmlAttributes); tagBuilder.MergeAttribute("name", name, true /* replaceExisting */); tagBuilder.GenerateId(name); if (allowsMultipleValues) { tagBuilder.MergeAttribute("multiple", "multiple"); } ModelState modelState; if (htmlHelper.ViewData.ModelState.TryGetValue(name, out modelState)) { if (modelState.Errors.Count > 0) { tagBuilder.AddCssClass(HtmlHelper.ValidationInputCssClassName); } } tagBuilder.MergeAttributes(MvcEnvironment.GetUnobtrusiveValidation(htmlHelper, partialName, metaData)); return(MvcHtmlString.Create(tagBuilder.ToString())); }
public static MvcHtmlString SortableListFor <VM, TItem>( this HtmlHelper <VM> htmlHelper, RenderInfo <IEnumerable <TItem> > renderInfo, object template, object addElementTemplate = null, float opacity = 1, bool canSort = true, IDictionary <string, object> htmlAttributesContainer = null, IDictionary <string, object> htmlAttributesItems = null, bool enableMultipleInsert = true, ExternalContainerType itemContainer = ExternalContainerType.li, ExternalContainerType allItemsContainer = ExternalContainerType.ul, object headerTemplate = null, object footerTemplate = null, string itemCss = null, string altItemCss = null, bool displayOnly = false, string sortableHandle = null, Func <TItem, int> templateSelector = null, Func <int, IDictionary <string, object> > htmlAttributesSelector = null ) { if (template == null) { throw (new ArgumentNullException("template")); } if (renderInfo == null) { throw (new ArgumentNullException("renderiNFO")); } if (string.IsNullOrWhiteSpace(itemCss)) { itemCss = string.Empty; } if (string.IsNullOrWhiteSpace(altItemCss)) { altItemCss = string.Empty; } if (displayOnly) { canSort = false; } if (canSort) { itemContainer = ExternalContainerType.li; allItemsContainer = ExternalContainerType.ul; headerTemplate = null; footerTemplate = null; htmlHelper.ViewData[renderInfo.Prefix + "_Rendering"] = "SortableList_Dragging"; } else { htmlHelper.ViewData[renderInfo.Prefix + "_Rendering"] = "SortableList_Dragging"; } bool multipleTemplates = false; if (template is string || !(template is object[])) { template = new object[] { template }; } else if (templateSelector != null) { multipleTemplates = true; } int nTemplates = (template as object[]).Length; Type[] allTypes = new Type[nTemplates]; int tcount = 0; foreach (object t in (template as object[])) { if (t is string) { allTypes[tcount] = typeof(TItem); } else { allTypes[tcount] = TemplateInvoker <string> .ExtractModelType(t); } tcount++; } StringBuilder sb = new StringBuilder(); StringBuilder sbInit = new StringBuilder(); sbInit.Append(renderInfo.PartialRendering); if (htmlAttributesContainer == null) { htmlAttributesContainer = new Dictionary <string, object>(); } htmlAttributesContainer["id"] = BasicHtmlHelper.IdFromName(renderInfo.Prefix) + "_ItemsContainer"; string externalOpenTag = null; string externalCloseTag = null; string itemOpenTag = null; string itemCloseTag = null; BasicHtmlHelper.GetContainerTags(allItemsContainer, htmlAttributesContainer, out externalOpenTag, out externalCloseTag); sb.Append(externalOpenTag); if (htmlAttributesItems == null) { htmlAttributesItems = new Dictionary <string, object>(); } IDictionary <string, object> fixedHtmlAttributesItems = htmlAttributesItems; bool templateEnabled = false; string addItemScriptFormat = addItemJQueryScriptFormat; switch (MvcEnvironment.Validation(htmlHelper)) { case ValidationType.StandardClient: break; case ValidationType.UnobtrusiveClient: templateEnabled = true; break; default: templateEnabled = true; break; } templateEnabled = templateEnabled && enableMultipleInsert; int totalCount = 0; string javasctiptOpacity = string.Empty; string javascriptHandle = string.Empty; string permutationElementPrefix = null; if (renderInfo.Model == null) { renderInfo.Model = new List <TItem>(); } if (renderInfo.Model != null) { if (headerTemplate != null) { if (multipleTemplates) { htmlAttributesItems = dictionarySelection(htmlAttributesSelector, fixedHtmlAttributesItems, -1); } ViewDataDictionary <TItem> dataDictionary = new ViewDataDictionary <TItem>(); dataDictionary.TemplateInfo.HtmlFieldPrefix = renderInfo.Prefix; if (htmlHelper.ViewData.ContainsKey("ThemeParams")) { dataDictionary["ThemeParams"] = htmlHelper.ViewData["ThemeParams"]; } BasicHtmlHelper.CopyRelevantErrors(dataDictionary.ModelState, htmlHelper.ViewData.ModelState, dataDictionary.TemplateInfo.HtmlFieldPrefix); htmlAttributesItems["id"] = BasicHtmlHelper.IdFromName(BasicHtmlHelper.AddField(renderInfo.Prefix, "Header")); BasicHtmlHelper.GetContainerTags(itemContainer, htmlAttributesItems, out itemOpenTag, out itemCloseTag); sb.Append(itemOpenTag); sb.Append(new TemplateInvoker <TItem>(headerTemplate).Invoke <VM>(htmlHelper, dataDictionary)); sb.Append(itemCloseTag); } foreach (TItem x in renderInfo.Model) { if (x == null && htmlHelper.ViewContext.ViewData.ModelState.IsValid) { continue; } totalCount++; int templateIndex = 0; Type currType = typeof(TItem); if (multipleTemplates) { templateIndex = templateSelector(x); currType = allTypes[templateIndex]; htmlAttributesItems = dictionarySelection(htmlAttributesSelector, fixedHtmlAttributesItems, templateIndex); } IUpdateModel um = null; if (x == null) { um = typeof(AutoEnumerableUpdater <string>).GetGenericTypeDefinition().MakeGenericType(currType) .GetConstructor(new Type[0]).Invoke(new object[0]) as IUpdateModel; } else if (x.GetType() == typeof(TItem)) { um = new AutoEnumerableUpdater <TItem>(); } else { um = typeof(AutoEnumerableUpdater <string>).GetGenericTypeDefinition().MakeGenericType(x.GetType()) .GetConstructor(new Type[0]).Invoke(new object[0]) as IUpdateModel; } um.ImportFromModel(x, null, null, new object[0]); string prefix = renderInfo.Prefix; string partialPrefix = renderInfo.PartialPrefix; string updateInfo = BasicHtmlHelper.RenderUpdateInfo <TItem>(htmlHelper, um, ref partialPrefix, new string[0]); if (!displayOnly) { sbInit.Append(updateInfo); } prefix = htmlHelper.ViewData.TemplateInfo.GetFullHtmlFieldName(partialPrefix); object currTemplate = (template as object[])[templateIndex]; ViewDataDictionary dataDictionary = null; ITemplateInvoker currInvoker = null; if (allTypes[templateIndex] == typeof(TItem)) { dataDictionary = new ViewDataDictionary <TItem>(x); currInvoker = new TemplateInvoker <TItem>(currTemplate); } else { dataDictionary = typeof(ViewDataDictionary <string>).GetGenericTypeDefinition().MakeGenericType(allTypes[templateIndex]) .GetConstructor(new Type[] { allTypes[templateIndex] }).Invoke(new object[] { x }) as ViewDataDictionary; currInvoker = typeof(TemplateInvoker <string>).GetGenericTypeDefinition().MakeGenericType(allTypes[templateIndex]) .GetConstructor(new Type[] { typeof(object) }).Invoke(new object[] { currTemplate }) as ITemplateInvoker; } dataDictionary.TemplateInfo.HtmlFieldPrefix = BasicHtmlHelper.AddField(prefix, "$.Item"); if (htmlHelper.ViewData.ContainsKey("ThemeParams")) { dataDictionary["ThemeParams"] = htmlHelper.ViewData["ThemeParams"]; } BasicHtmlHelper.CopyRelevantErrors(dataDictionary.ModelState, htmlHelper.ViewData.ModelState, dataDictionary.TemplateInfo.HtmlFieldPrefix); htmlAttributesItems["id"] = BasicHtmlHelper.IdFromName(BasicHtmlHelper.AddField(prefix, "$.Item")) + "_Container"; BasicHtmlHelper.GetContainerTags(itemContainer, htmlAttributesItems, out itemOpenTag, out itemCloseTag); sb.Append(itemOpenTag); sb.Append(currInvoker.Invoke <VM>(htmlHelper, dataDictionary)); sb.Append(itemCloseTag); } } string delayedRendering = null; if (addElementTemplate != null && !templateEnabled) { EnumerableUpdater <TItem> um = new EnumerableUpdater <TItem>(true); string prefix = renderInfo.Prefix; string partialPrefix = renderInfo.PartialPrefix; sbInit.Append( BasicHtmlHelper.RenderUpdateInfo <TItem>(htmlHelper, um, ref partialPrefix, new string[0])); prefix = htmlHelper.ViewData.TemplateInfo.GetFullHtmlFieldName(partialPrefix); sbInit.Append(htmlHelper.GenericInput(InputType.Hidden, BasicHtmlHelper.AddField(partialPrefix, "$.Deleted"), um.Deleted, null)); delayedRendering = string.Format( addItemScriptFormat, BasicHtmlHelper.IdFromName(BasicHtmlHelper.AddField(prefix, "$.Item.InnerContainer"))); ViewDataDictionary <TItem> dataDictionary = new ViewDataDictionary <TItem>(um.Item); dataDictionary.TemplateInfo.HtmlFieldPrefix = BasicHtmlHelper.AddField(prefix, "$.Item"); if (htmlHelper.ViewData.ContainsKey("ThemeParams")) { dataDictionary["ThemeParams"] = htmlHelper.ViewData["ThemeParams"]; } BasicHtmlHelper.CopyRelevantErrors(dataDictionary.ModelState, htmlHelper.ViewData.ModelState, dataDictionary.TemplateInfo.HtmlFieldPrefix); htmlAttributesItems["id"] = BasicHtmlHelper.IdFromName(BasicHtmlHelper.AddField(prefix, "$.Item")) + "_Container"; BasicHtmlHelper.GetContainerTags(itemContainer, htmlAttributesItems, out itemOpenTag, out itemCloseTag); sb.Append(itemOpenTag); sb.Append(new TemplateInvoker <TItem>(addElementTemplate).Invoke <VM>(htmlHelper, dataDictionary)); sb.Append(itemCloseTag); } if (canSort) { PermutationsUpdater <TItem> um = new PermutationsUpdater <TItem>(); um.ImportFromModel(null, null, null, new object[0]); string prefix = renderInfo.Prefix; string partialPrefix = renderInfo.PartialPrefix; sbInit.Append( BasicHtmlHelper.RenderUpdateInfo <TItem>(htmlHelper, um, ref partialPrefix, new string[0])); prefix = htmlHelper.ViewData.TemplateInfo.GetFullHtmlFieldName(partialPrefix); sbInit.Append( string.Format("<input type='hidden' id={0} name={1} value=''/>", BasicHtmlHelper.IdFromName(renderInfo.Prefix + "_Permutation"), BasicHtmlHelper.AddField(prefix, "$.Permutation"))); if (opacity > 1f) { opacity = 1f; } else if (opacity < 0.01f) { opacity = 0.01f; } if (opacity < 1f) { javasctiptOpacity = string.Format(" opacity: {0}, ", opacity.ToString(CultureInfo.InvariantCulture)); } if (sortableHandle != null) { javascriptHandle = string.Format(" handle: '{0}', ", sortableHandle); } permutationElementPrefix = prefix; } if (footerTemplate != null) { if (multipleTemplates) { htmlAttributesItems = dictionarySelection(htmlAttributesSelector, fixedHtmlAttributesItems, -2); } ViewDataDictionary <TItem> dataDictionary = new ViewDataDictionary <TItem>(); dataDictionary.TemplateInfo.HtmlFieldPrefix = renderInfo.Prefix; if (htmlHelper.ViewData.ContainsKey("ThemeParams")) { dataDictionary["ThemeParams"] = htmlHelper.ViewData["ThemeParams"]; } BasicHtmlHelper.CopyRelevantErrors(dataDictionary.ModelState, htmlHelper.ViewData.ModelState, dataDictionary.TemplateInfo.HtmlFieldPrefix); htmlAttributesItems["id"] = BasicHtmlHelper.IdFromName(BasicHtmlHelper.AddField(renderInfo.Prefix, "Footer")); BasicHtmlHelper.GetContainerTags(itemContainer, htmlAttributesItems, out itemOpenTag, out itemCloseTag); sb.Append(itemOpenTag); sb.Append(new TemplateInvoker <TItem>(footerTemplate).Invoke <VM>(htmlHelper, dataDictionary)); sb.Append(itemCloseTag); } if (templateEnabled) { IUpdateModel um = null; TItem dummyItem = default(TItem); object[] allTemplates = template as object[]; StringBuilder alltemplateNames = new StringBuilder(); StringBuilder allhiddenNames = new StringBuilder(); StringBuilder allsymbolNames = new StringBuilder(); string basicTemplateSymbol = BasicHtmlHelper.GetUniqueSymbol(htmlHelper, templateSymbol); for (int i = 0; i < allTemplates.Length; i++) { if (multipleTemplates) { htmlAttributesItems = dictionarySelection(htmlAttributesSelector, fixedHtmlAttributesItems, i); } if (allTypes[i] == typeof(TItem)) { um = new AutoEnumerableUpdater <TItem>(); } else { um = typeof(AutoEnumerableUpdater <string>).GetGenericTypeDefinition().MakeGenericType(allTypes[i]) .GetConstructor(new Type[0]).Invoke(new object[0]) as IUpdateModel; } string prefix = renderInfo.Prefix; string partialPrefix = renderInfo.PartialPrefix; string myTemplateSymbol = basicTemplateSymbol + i.ToString(CultureInfo.InvariantCulture); sbInit.Append( BasicHtmlHelper.RenderUpdateInfoI(htmlHelper, um, ref partialPrefix, new string[0], myTemplateSymbol)); prefix = htmlHelper.ViewData.TemplateInfo.GetFullHtmlFieldName(partialPrefix); ViewDataDictionary dataDictionary = null; ITemplateInvoker currInvoker = null; if (allTypes[i] == typeof(TItem)) { dataDictionary = new ViewDataDictionary <TItem>(dummyItem); currInvoker = new TemplateInvoker <TItem>(allTemplates[i]); } else { dataDictionary = typeof(ViewDataDictionary <string>).GetGenericTypeDefinition().MakeGenericType(allTypes[i]) .GetConstructor(new Type[] { allTypes[i] }).Invoke(new object[] { dummyItem }) as ViewDataDictionary; currInvoker = typeof(TemplateInvoker <string>).GetGenericTypeDefinition().MakeGenericType(allTypes[i]) .GetConstructor(new Type[] { typeof(object) }).Invoke(new object[] { allTemplates[i] }) as ITemplateInvoker; } dataDictionary.TemplateInfo.HtmlFieldPrefix = BasicHtmlHelper.AddField(prefix, "$.Item"); if (htmlHelper.ViewData.ContainsKey("ThemeParams")) { dataDictionary["ThemeParams"] = htmlHelper.ViewData["ThemeParams"]; } BasicHtmlHelper.CopyRelevantErrors(dataDictionary.ModelState, htmlHelper.ViewData.ModelState, dataDictionary.TemplateInfo.HtmlFieldPrefix); string templateId = BasicHtmlHelper.IdFromName(BasicHtmlHelper.AddField(prefix, "$.Item")) + "_Container"; htmlAttributesItems["id"] = templateId; if (i > 0) { alltemplateNames.Append(", "); allhiddenNames.Append(", "); allsymbolNames.Append(", "); } alltemplateNames.Append("'"); alltemplateNames.Append(templateId); alltemplateNames.Append("'"); allhiddenNames.Append("'"); allhiddenNames.Append(BasicHtmlHelper.IdFromName(prefix)); allhiddenNames.Append("'"); allsymbolNames.Append("/"); allsymbolNames.Append(myTemplateSymbol); allsymbolNames.Append("/g"); BasicHtmlHelper.GetContainerTags(itemContainer, htmlAttributesItems, out itemOpenTag, out itemCloseTag); sb.Append(string.Format("<span id='{0}' style='display:none' class='MVCCT_EncodedTemplate'>", templateId)); sb.Append(htmlHelper.Encode(itemOpenTag)); sb.Append(htmlHelper.Encode(currInvoker.Invoke <VM>(htmlHelper, dataDictionary))); sb.Append(htmlHelper.Encode(itemCloseTag)); sb.Append("</span>"); } sbInit.Append(string.Format(startTemplateScriptFormat, BasicHtmlHelper.IdFromName(renderInfo.Prefix), canSort ? "true" : "false", totalCount, allsymbolNames.ToString(), alltemplateNames.ToString(), allhiddenNames.ToString(), renderInfo.Prefix)); } if (canSort) { sbInit.Append(string.Format(startScriptFormat, BasicHtmlHelper.IdFromName(renderInfo.Prefix), javascriptHandle + javasctiptOpacity, BasicHtmlHelper.IdFromName(permutationElementPrefix))); } string stylingJavaScript = string.Format(stylingScript, BasicHtmlHelper.IdFromName(renderInfo.Prefix), itemCss, altItemCss); sbInit.Append(stylingJavaScript); if (delayedRendering != null) { sbInit.Append(delayedRendering); } sb.Append(externalCloseTag); sbInit.Insert(0, sb.ToString()); return(MvcHtmlString.Create(sbInit.ToString())); }
internal static IBindingsBuilder <T> InnerClientViewModel <T>( this HtmlHelper htmlHelper, string uniqueName, T model, string partialPrefix, string prefix, string htmlElementId, bool initialSave, bool applyBindings, bool applyDependencies = true ) where T : class, new() { if (partialPrefix == null) { partialPrefix = string.Empty; } if (prefix == null) { prefix = string.Empty; } if (uniqueName == null) { throw (new ArgumentNullException("uniqueName")); } string validationType = null; switch (MvcEnvironment.Validation(htmlHelper)) { case ValidationType.StandardClient: validationType = "StandardClient"; break; case ValidationType.UnobtrusiveClient: validationType = "UnobtrusiveClient"; break; default: validationType = "Server"; break; } if (model == null) { return(new BindingsBuilder <T>(null, uniqueName, prefix, validationType, null, htmlHelper)); } string script = null; if (applyBindings) { if (htmlElementId == null) { script = rootBingingScript; } else { script = elementBingingScript; } } else if (applyDependencies) { script = modelScript; } else { script = modelScriptNoDep; } ModelTranslator <T> translator = new ModelTranslator <T>(); translator.ImportFromModel(model); htmlHelper.ViewContext.Writer.Write( BasicHtmlHelper.RenderDisplayInfo(htmlHelper, typeof(ModelTranslator <T>), partialPrefix, true)); object ocount = htmlHelper.ViewContext.Controller.ViewData["__ClientModelsCount__"]; int count = 0; if (ocount != null) { count = (int)ocount; } count++; htmlHelper.ViewContext.Controller.ViewData["__ClientModelsCount__"] = count; string jsonHiddenId = BasicHtmlHelper.IdFromName( BasicHtmlHelper.AddField(prefix, "$.JSonModel" + count.ToString())); htmlHelper.ViewContext.Writer.Write( BasicHtmlHelper.SafeHiddenUC(htmlHelper, BasicHtmlHelper.AddField(partialPrefix, "$.JSonModel"), string.Empty, jsonHiddenId ) ); string saveScript = string.Empty; if (initialSave) { saveScript = uniqueName + ".save();"; } string assignement = uniqueName; if (!assignement.Contains('.')) { assignement = "var " + assignement; } string jsonModel = string.Format(script, assignement, uniqueName, translator.JSonModel, saveScript, htmlElementId, jsonHiddenId, validationType); htmlHelper.ViewContext.Writer.Write(jsonModel); IBindingsBuilder <T> result = new BindingsBuilder <T>(htmlHelper.ViewContext.Writer, uniqueName, prefix, validationType, jsonHiddenId, htmlHelper); /* result.AddMethod("save", string.Format(@" * function(){{ * document.getElementById('{0}').value = ko.mapping.toJSON(this); * }}", * jsonHiddenId)); * result.AddMethod("validateAndSave", string.Format(@" * function(){{ * if(MvcControlsToolkit_FormIsValid('{0}', '{1}')){{ * document.getElementById('{0}').value = ko.mapping.toJSON(this); * return true; * }} * return false; * }}", * jsonHiddenId, validationType)); * result.AddMethod("saveAndSubmit", string.Format(@" * function(){{ * if(this.validateAndSave()){{ * $('#{0}').parents('form').submit(); * }} * }}", * jsonHiddenId * )); * result.AddMethod("saveAndSubmitAlone", string.Format(@" * function(formId){{ * if(MvcControlsToolkit_FormIsValid(formId, '{1}')){{ * this.save(); * $('#{0}').parents('form').submit(); * }} * }}", * jsonHiddenId, * validationType * )); */ return(result); }
public static MvcHtmlString DetailLink <TItem>( this HtmlHelper <TItem> htmlHelper, AjaxHelper ajax, string text, DetailType detailType, string controllerAction, string controllerName, object parameters, string loadingElementId, IDictionary <string, object> htmlAttributes = null) { if (ajax == null) { throw (new ArgumentNullException("ajax")); } if (text == null) { throw (new ArgumentNullException("text")); } if (controllerAction == null) { throw (new ArgumentNullException("ControllerAction")); } if (controllerName == null) { throw (new ArgumentNullException("ControllerName")); } string status = null; bool visible = true; if (htmlHelper.ViewData.ContainsKey("status")) { status = htmlHelper.ViewData["status"] as string; } string detail = "Display"; if (status == "InsertItem") { if (detailType == DetailType.Edit) { detail = "Insert"; } else { visible = false; } } else if (status == "Insert" || status == "Phantom") { visible = false; } else if (detailType == DetailType.Edit) { detail = "FirstEdit"; } if (!visible) { return(MvcHtmlString.Create(string.Empty)); } string rootItemName = BasicHtmlHelper.IdFromName(htmlHelper.ViewData.TemplateInfo.HtmlFieldPrefix); string baseName = rootItemName.Substring(0, rootItemName.LastIndexOf("___")); baseName = baseName.Substring(0, baseName.LastIndexOf("___")); string containerName = baseName + "_Container"; string onSuccessName = baseName + "_OnSuccess"; string onFailureName = baseName + "_OnFailure"; string onBeginScript = MvcEnvironment.UnobtrusiveAjaxOn(htmlHelper) ? "return OnBeginDetailForm('{0}', '{1}', '{2}', '{3}', null);" : "function() {{ return OnBeginDetailForm('{0}', '{1}', '{2}', '{3}', null); }}"; return(ajax.ActionLink(text, controllerAction, controllerName, parameters, new AjaxOptions() { HttpMethod = "Get", UpdateTargetId = containerName, LoadingElementId = loadingElementId, OnSuccess = onSuccessName, OnBegin = string.Format( onBeginScript, baseName, detail, rootItemName, loadingElementId), OnFailure = onFailureName, InsertionMode = InsertionMode.Replace }, htmlAttributes)); }
public static void DetailFormFor <VM, TItem>( this HtmlHelper <VM> htmlHelper, AjaxHelper <VM> ajax, RenderInfo <IEnumerable <Tracker <TItem> > > renderInfo, ExternalContainerType externalContainerType, string postActionName, string postControllerName, string detailPrefix = null, string changedFieldCss = null, string deletedRecordCss = null, IDictionary <string, object> externalContainerHtmlattributes = null, string clientOnSuccessEdit = null, string clientOnFailureEdit = null, string clientOnSuccessDisplay = null, string clientOnFailureDisplay = null, string loadingElementId = null, Dialog detailDialog = null ) where TItem : class, new() { if (renderInfo == null) { throw (new ArgumentNullException("renderInfo")); } if (ajax == null) { throw (new ArgumentNullException("ajax")); } if (postActionName == null) { throw (new ArgumentNullException("postActionName")); } if (postControllerName == null) { throw (new ArgumentNullException("postControllerName")); } if (externalContainerHtmlattributes == null) { externalContainerHtmlattributes = new Dictionary <string, object>(); } string baseName = BasicHtmlHelper.IdFromName(renderInfo.Prefix); string formName = baseName + "_AjaxForm"; string containerName = baseName + "_Container"; string onSuccessName = baseName + "_OnSuccess"; string onFailureName = baseName + "_OnFailure"; string onBeginName = baseName + "_OnBegin"; string beginTag; string closeTag; externalContainerHtmlattributes["id"] = containerName; BasicHtmlHelper.GetContainerTags(externalContainerType, externalContainerHtmlattributes, out beginTag, out closeTag); string javascriptChangedFieldCss = changedFieldCss == null ? "null" : "'" + changedFieldCss + "'"; string javascriptDeletedRecordCss = deletedRecordCss == null ? "null" : "'" + deletedRecordCss + "'"; string javascriptClientOnSuccessEdit = clientOnSuccessEdit == null ? "null" : "'" + clientOnSuccessEdit + "'"; string javascriptClientOnSuccessDisplay = clientOnSuccessDisplay == null ? "null" : "'" + clientOnSuccessDisplay + "'"; string javascriptClientOnFailureEdit = clientOnFailureEdit == null ? "null" : "'" + clientOnFailureEdit + "'"; string javascriptClientOnFailureDisplay = clientOnFailureDisplay == null ? "null" : "'" + clientOnFailureDisplay + "'"; if (detailPrefix == null) { detailPrefix = string.Empty; } string validationType = null; string unobtrusiveAjaxOn = "false"; if (MvcEnvironment.UnobtrusiveAjaxOn(htmlHelper)) { unobtrusiveAjaxOn = "true"; } switch (MvcEnvironment.Validation(htmlHelper)) { case ValidationType.StandardClient: validationType = "StandardClient"; break; case ValidationType.UnobtrusiveClient: validationType = "UnobtrusiveClient"; break; default: validationType = "Server"; break; } htmlHelper.ViewContext.Writer.Write( string.Format(prefixTranslationScript, baseName, BasicHtmlHelper.IdFromName(detailPrefix))); PropertyInfo[] propertiesToUpdate = BasicHtmlHelper.GetPropertiesForInput(typeof(TItem)); StringBuilder sb = new StringBuilder(); Stack <Type> recursionControl = new Stack <Type>(); recursionControl.Push(typeof(TItem)); getPropertiesToUpdate( sb, string.Empty, propertiesToUpdate, recursionControl); recursionControl.Pop(); object formHtmlAttributes = null; if (formName != null) { formHtmlAttributes = new { id = formName }; } htmlHelper.ViewContext.Writer.Write( string.Format(fieldsToUpdateScript, baseName, sb.ToString(), javascriptChangedFieldCss, javascriptDeletedRecordCss)); htmlHelper.ViewContext.Writer.Write( string.Format(onBeginScript, onBeginName, baseName, "Edit", "null", loadingElementId, validationType)); string dialogOpen; if (detailDialog == null) { dialogOpen = string.Empty; } else { dialogOpen = detailDialog.GetShow('#' + formName); } htmlHelper.ViewContext.Writer.Write( string.Format(onSuccessScript, onSuccessName, baseName, javascriptClientOnSuccessDisplay, javascriptClientOnSuccessEdit, dialogOpen, formName, validationType, unobtrusiveAjaxOn, containerName)); htmlHelper.ViewContext.Writer.Write( string.Format(onFailureScript, onFailureName, baseName, javascriptClientOnFailureDisplay, javascriptClientOnFailureEdit)); if (detailDialog != null) { htmlHelper.ViewContext.Writer.Write(detailDialog.GetCreation('#' + formName)); } using (var form = ajax.BeginForm( postActionName, postControllerName, new AjaxOptions() { HttpMethod = "Post", UpdateTargetId = unobtrusiveAjaxOn == "true" ? null : containerName, LoadingElementId = loadingElementId, OnSuccess = onSuccessName, OnBegin = onBeginName, OnFailure = onFailureName, InsertionMode = InsertionMode.Replace }, formHtmlAttributes)) { htmlHelper.ViewContext.Writer.Write(beginTag); htmlHelper.ViewContext.Writer.Write(closeTag); } if (!MvcEnvironment.UnobtrusiveAjaxOn(htmlHelper)) { htmlHelper.ViewContext.Writer.Write( htmlHelper.AjaxSubmitEnabler(formName, false).ToString()); } }