public async Task ProcessAsync_GeneratesAntiforgeryCorrectly( bool?antiforgery, FormMethod method, string expectedPostContent) { // Arrange var viewContext = CreateViewContext(); var expectedAttribute = new TagHelperAttribute("method", method.ToString().ToLowerInvariant()); var context = new TagHelperContext( tagName: "form", allAttributes: new TagHelperAttributeList(new[] { expectedAttribute }), items: new Dictionary <object, object>(), uniqueId: "test"); var output = new TagHelperOutput( "form", attributes: new TagHelperAttributeList(), getChildContentAsync: (useCachedResult, encoder) => { var tagHelperContent = new DefaultTagHelperContent(); tagHelperContent.SetContent("Something"); return(Task.FromResult <TagHelperContent>(tagHelperContent)); }); var generator = new Mock <IHtmlGenerator>(MockBehavior.Strict); generator .Setup(mock => mock.GenerateForm( It.IsAny <ViewContext>(), It.IsAny <string>(), It.IsAny <string>(), It.IsAny <object>(), It.IsAny <string>(), It.IsAny <object>())) .Returns(new TagBuilder("form")); generator.Setup(mock => mock.GenerateAntiforgery(viewContext)) .Returns(new HtmlString("<input />")); var formTagHelper = new FormTagHelper(generator.Object) { Action = "Index", Antiforgery = antiforgery, ViewContext = viewContext, Method = method.ToString().ToLowerInvariant() }; // Act await formTagHelper.ProcessAsync(context, output); // Assert Assert.Equal("form", output.TagName); Assert.Equal(TagMode.StartTagAndEndTag, output.TagMode); var attribute = Assert.Single(output.Attributes); Assert.Equal(expectedAttribute, attribute); Assert.Empty(output.PreContent.GetContent()); Assert.True(output.Content.GetContent().Length == 0); Assert.Equal(expectedPostContent, output.PostContent.GetContent()); }
public FormContainer(HtmlTextWriter htmlTextWriter, string url , BootstrapFormType formType = BootstrapFormType.Horizontal, FormMethod method = FormMethod.Post, object htmlAttributes = null) { this.textWriter = htmlTextWriter; this.formType = formType; textWriter.AddAttribute("method", method.ToString()); textWriter.AddAttribute("action", url ) ; var htmlAttributesCollection = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes); switch (this.formType) { case BootstrapFormType.Horizontal: htmlAttributesCollection.Merge("class", "form-horizontal"); break; case BootstrapFormType.Vertical: htmlAttributesCollection.Merge("class", "form-vertical"); break; case BootstrapFormType.Inline: htmlAttributesCollection.Merge("class", "form-inline"); break; } foreach (var htmlAttribute in htmlAttributesCollection) { textWriter.AddAttribute(htmlAttribute.Key, htmlAttribute.Value.ToString()); } textWriter.RenderBeginTag(HtmlTextWriterTag.Form); }
public void BeginRouteFormWithRouteNameMethodAndHtmlAttributesParameters_CallsHtmlGeneratorWithExpectedValues( string routeName, FormMethod method, object htmlAttributes) { // Arrange var tagBuilder = new TagBuilder(tagName: "form"); var htmlGenerator = new Mock <IHtmlGenerator>(MockBehavior.Strict); var htmlHelper = DefaultTemplatesUtilities.GetHtmlHelper(htmlGenerator.Object); htmlGenerator .Setup(realHelper => realHelper.GenerateRouteForm( htmlHelper.ViewContext, routeName, null, // routeValues method.ToString().ToLowerInvariant(), htmlAttributes)) .Returns(tagBuilder) .Verifiable(); // Guards Assert.NotNull(htmlHelper.ViewContext); var writer = Assert.IsAssignableFrom <StringWriter>(htmlHelper.ViewContext.Writer); var builder = writer.GetStringBuilder(); Assert.NotNull(builder); // Act var mvcForm = htmlHelper.BeginRouteForm(routeName, method, htmlAttributes); // Assert Assert.NotNull(mvcForm); Assert.Equal("<form>", builder.ToString()); htmlGenerator.Verify(); }
public void BeginFormWithMethodParameter_CallsHtmlGeneratorWithExpectedValues(FormMethod method) { // Arrange var tagBuilder = new TagBuilder(tagName: "form", htmlEncoder: new NullTestEncoder()); var htmlGenerator = new Mock <IHtmlGenerator>(MockBehavior.Strict); var htmlHelper = DefaultTemplatesUtilities.GetHtmlHelper(htmlGenerator.Object); htmlGenerator .Setup(realHelper => realHelper.GenerateForm( htmlHelper.ViewContext, null, // actionName null, // controllerName null, // routeValues method.ToString().ToLowerInvariant(), null)) // htmlAttributes .Returns(tagBuilder) .Verifiable(); // Guards Assert.NotNull(htmlHelper.ViewContext); var writer = Assert.IsAssignableFrom <StringWriter>(htmlHelper.ViewContext.Writer); var builder = writer.GetStringBuilder(); Assert.NotNull(builder); // Act var mvcForm = htmlHelper.BeginForm(method); // Assert Assert.NotNull(mvcForm); Assert.Equal("<form>", builder.ToString()); htmlGenerator.Verify(); }
public FormContainer(HtmlTextWriter htmlTextWriter, string url, BootstrapFormType formType = BootstrapFormType.Horizontal, FormMethod method = FormMethod.Post, object htmlAttributes = null) { this.textWriter = htmlTextWriter; this.formType = formType; textWriter.AddAttribute("method", method.ToString()); textWriter.AddAttribute("action", url); var htmlAttributesCollection = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes); switch (this.formType) { case BootstrapFormType.Horizontal: htmlAttributesCollection.Merge("class", "form-horizontal"); break; case BootstrapFormType.Vertical: htmlAttributesCollection.Merge("class", "form-vertical"); break; case BootstrapFormType.Inline: htmlAttributesCollection.Merge("class", "form-inline"); break; } foreach (var htmlAttribute in htmlAttributesCollection) { textWriter.AddAttribute(htmlAttribute.Key, htmlAttribute.Value.ToString()); } textWriter.RenderBeginTag(HtmlTextWriterTag.Form); }
public CreaDevAjaxOptions(string targetElementSelector, string alertSelector, string modalToHideSelector, FormMethod httpMethod = FormMethod.Post) { this.HttpMethod = httpMethod.ToString(); this.OnBegin = $"block('{targetElementSelector}');"; this.OnFailure = $"onAjaxFailed(xhr, status, error, '{alertSelector}'); "; this.OnComplete = $"onAjaxComplete(xhr, status,'{targetElementSelector}','{alertSelector}','{targetElementSelector}');"; this.OnSuccess = $"onAjaxSuccess(xhr,status,'{modalToHideSelector}');"; }
public static MvcHtmlString Button(this HtmlHelper helper, string text, string urlAction, FormMethod method, object htmlAttributes) { var tagBuilder = new TagBuilder("input"); FillWithAttributes(tagBuilder, new { type = "submit", formaction = urlAction, formmethod = method.ToString(), value = text }); FillWithAttributes(tagBuilder, htmlAttributes); return new MvcHtmlString(tagBuilder.ToString()); }
public CreaDevAjaxOptions(string elementToReplace, string elementToBlock, string alertElement = "#alert", string modelToHide = "", string onCompleteMethod = null, string dataCallbackMethod = null, FormMethod httpMethod = FormMethod.Post) { string callbackMethod = !string.IsNullOrWhiteSpace(dataCallbackMethod) ? dataCallbackMethod : "null"; this.HttpMethod = httpMethod.ToString(); this.OnBegin = $"block('{elementToBlock}');"; this.OnFailure = $"onAjaxFailed(xhr, status, error, '{alertElement}'); "; this.OnComplete = $"onAjaxComplete(xhr, status,'{elementToBlock}','{alertElement}','{elementToReplace}','null',{callbackMethod});{onCompleteMethod ?? ""}"; this.OnSuccess = $"onAjaxSuccess(xhr,status,'{modelToHide}');"; }
public static TagBuilder FormForButton(this HtmlHelper helper, FormMethod method, string actionName, string controllerName, object routeValues = null, object htmlAttributes = null) { var formBuilder = new TagBuilder("form"); formBuilder.MergeAttributes(HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes)); formBuilder.MergeAttribute("method", method.ToString()); var urlHelper = new UrlHelper(helper.ViewContext.RequestContext); formBuilder.Attributes.Add("action", urlHelper.Action(actionName, controllerName, routeValues)); return(formBuilder); }
public void BeginForm_RendersExpectedValues( string actionName, string controllerName, object routeValues, FormMethod method, object htmlAttributes) { // Arrange var expectedAction = "http://localhost/Hello/World"; var expectedStartTag = string.Format( CultureInfo.InvariantCulture, "<form action=\"HtmlEncode[[{0}]]\" method=\"HtmlEncode[[{1}]]\"{2}>", expectedAction, method.ToString().ToLowerInvariant(), GetHtmlAttributesAsString(htmlAttributes)); var urlHelper = new Mock <IUrlHelper>(MockBehavior.Strict); urlHelper .Setup(realHelper => realHelper.Action(It.Is <UrlActionContext>((context) => string.Equals(context.Action, actionName) && string.Equals(context.Controller, controllerName) && context.Values == routeValues ))) .Returns(expectedAction) .Verifiable(); var htmlHelper = DefaultTemplatesUtilities.GetHtmlHelper(urlHelper.Object); // Guards Assert.NotNull(htmlHelper.ViewContext); var writer = Assert.IsAssignableFrom <StringWriter>(htmlHelper.ViewContext.Writer); var builder = writer.GetStringBuilder(); Assert.NotNull(builder); // Act var mvcForm = htmlHelper.BeginForm( actionName, controllerName, routeValues, method, antiforgery: false, htmlAttributes: htmlAttributes); // Assert Assert.NotNull(mvcForm); Assert.Equal(expectedStartTag, builder.ToString()); urlHelper.Verify(); }
public void BeginRouteForm_RendersExpectedValues( string routeName, object routeValues, FormMethod method, object htmlAttributes) { // Arrange var expectedAction = "http://localhost/Hello/World"; var expectedStartTag = string.Format( "<form action=\"HtmlEncode[[{0}]]\" method=\"HtmlEncode[[{1}]]\"{2}>", expectedAction, method.ToString().ToLowerInvariant(), GetHtmlAttributesAsString(htmlAttributes)); var urlHelper = new Mock <IUrlHelper>(MockBehavior.Strict); urlHelper .Setup(realHelper => realHelper.RouteUrl(It.Is <UrlRouteContext>(context => string.Equals(context.RouteName, routeName) && context.Values == routeValues && context.Protocol == null && context.Host == null && context.Fragment == null))) .Returns(expectedAction) .Verifiable(); var htmlHelper = DefaultTemplatesUtilities.GetHtmlHelper(urlHelper.Object); // Guards Assert.NotNull(htmlHelper.ViewContext); var writer = Assert.IsAssignableFrom <StringWriter>(htmlHelper.ViewContext.Writer); var builder = writer.GetStringBuilder(); Assert.NotNull(builder); // Act var mvcForm = htmlHelper.BeginRouteForm( routeName, routeValues, method, suppressAntiforgery: true, htmlAttributes: htmlAttributes); // Assert Assert.NotNull(mvcForm); Assert.Equal(expectedStartTag, builder.ToString()); urlHelper.Verify(); }
public void BeginFormWithActionNameControllerNameMethodAndHtmlAttributesParameters_WithAntiforgery_CallsHtmlGeneratorWithExpectedValues( string actionName, string controllerName, FormMethod method, object htmlAttributes) { // Arrange var tagBuilder = new TagBuilder(tagName: "form"); var htmlGenerator = new Mock <IHtmlGenerator>(MockBehavior.Strict); var htmlHelper = DefaultTemplatesUtilities.GetHtmlHelper(htmlGenerator.Object); htmlGenerator .Setup(g => g.GenerateForm( htmlHelper.ViewContext, actionName, controllerName, null, // routeValues method.ToString().ToLowerInvariant(), htmlAttributes)) .Returns(tagBuilder) .Verifiable(); htmlGenerator .Setup(g => g.GenerateAntiforgery(htmlHelper.ViewContext)) .Returns(HtmlString.Empty) .Verifiable(); // Guards Assert.NotNull(htmlHelper.ViewContext); var writer = Assert.IsAssignableFrom <StringWriter>(htmlHelper.ViewContext.Writer); var builder = writer.GetStringBuilder(); Assert.NotNull(builder); // Act var mvcForm = htmlHelper.BeginForm( actionName, controllerName, routeValues: null, method: method, antiforgery: true, htmlAttributes: htmlAttributes); // Assert Assert.NotNull(mvcForm); Assert.Equal("<form>", builder.ToString()); htmlGenerator.Verify(); }
public static T RealizarRequisicao <T, TParametro>(string endereco, TParametro parametros, FormMethod metodo = FormMethod.Post) where T : class { var parametrosJson = Json.Encode(parametros); var retorno = RequisitarString(endereco, metodo.ToString(), parametrosJson); if (typeof(T) == typeof(string)) { return(retorno == null ? null : (T)Convert.ChangeType(retorno, typeof(T))); } var jsonSerializer = new JavaScriptSerializer { MaxJsonLength = int.MaxValue }; return(retorno == null ? (T)Activator.CreateInstance(typeof(T)) : jsonSerializer.Deserialize <T>(retorno)); }
public void BeginForm_RendersExpectedValues( string actionName, string controllerName, object routeValues, FormMethod method, object htmlAttributes) { // Arrange var expectedAction = "http://localhost/Hello/World"; var expectedStartTag = string.Format( "<form action=\"{0}\" method=\"{1}\"{2}>", expectedAction, method.ToString().ToLowerInvariant(), GetHtmlAttributesAsString(htmlAttributes)); var urlHelper = new Mock <IUrlHelper>(MockBehavior.Strict); urlHelper .Setup(realHelper => realHelper.Action( actionName, controllerName, routeValues, null, // protocol null, // host null)) // fragment .Returns(expectedAction) .Verifiable(); var htmlHelper = DefaultTemplatesUtilities.GetHtmlHelper(urlHelper.Object); // Guards Assert.NotNull(htmlHelper.ViewContext); var writer = Assert.IsAssignableFrom <StringWriter>(htmlHelper.ViewContext.Writer); var builder = writer.GetStringBuilder(); Assert.NotNull(builder); // Act var mvcForm = htmlHelper.BeginForm(actionName, controllerName, routeValues, method, htmlAttributes); // Assert Assert.NotNull(mvcForm); Assert.Equal(expectedStartTag, builder.ToString()); urlHelper.Verify(); }
public void BeginRouteFormWithRouteNameRouteValuesAndMethodParameters_CallsHtmlGeneratorWithExpectedValues( string routeName, object routeValues, FormMethod method) { // Arrange var tagBuilder = new TagBuilder(tagName: "form"); var htmlGenerator = new Mock <IHtmlGenerator>(MockBehavior.Strict); var htmlHelper = DefaultTemplatesUtilities.GetHtmlHelper(htmlGenerator.Object); htmlGenerator .Setup(g => g.GenerateRouteForm( htmlHelper.ViewContext, routeName, routeValues, method.ToString().ToLowerInvariant(), null)) // htmlAttributes .Returns(tagBuilder) .Verifiable(); if (method != FormMethod.Get) { htmlGenerator .Setup(g => g.GenerateAntiforgery(htmlHelper.ViewContext)) .Returns(HtmlString.Empty) .Verifiable(); } // Guards Assert.NotNull(htmlHelper.ViewContext); var writer = Assert.IsAssignableFrom <StringWriter>(htmlHelper.ViewContext.Writer); var builder = writer.GetStringBuilder(); Assert.NotNull(builder); // Act var mvcForm = htmlHelper.BeginRouteForm(routeName, routeValues, method); // Assert Assert.NotNull(mvcForm); Assert.Equal("<form>", builder.ToString()); htmlGenerator.Verify(); }
public static MvcHtmlString FormWithRole(this HtmlHelper htmlHelper, string requiredRoleName, string actionName, string controllerName, string sumbitCaption, Object routeValues = null, Object htmlAttributes = null, FormMethod method = FormMethod.Post) { HttpContext context = HttpContext.Current; MvcHandler handler = context.Handler as MvcHandler; if (handler.RequestContext.HttpContext.User.Identity.IsAuthenticated) { if (handler.RequestContext.HttpContext.User.IsInRole(requiredRoleName)) { var tag = new TagBuilder("form"); tag.MergeAttribute("method", method.ToString()); var helper = new UrlHelper(htmlHelper.ViewContext.RequestContext); var url = helper.Action(actionName, controllerName, routeValues); tag.MergeAttribute("action", url); var attributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes); foreach (var attribute in attributes) { tag.MergeAttribute(attribute.Key.ToString(), attribute.Value.ToString()); } var button = new TagBuilder("button"); button.MergeAttribute("type", "sumbit"); button.MergeAttribute("class", "btn btn-default"); button.InnerHtml = sumbitCaption; tag.InnerHtml += button.ToString(); return(MvcHtmlString.Create(tag.ToString())); } } return(MvcHtmlString.Empty); }
public async Task ProcessAsync_GeneratesAntiforgeryCorrectly( bool? antiforgery, FormMethod method, string expectedPostContent) { // Arrange var viewContext = CreateViewContext(); var expectedAttribute = new TagHelperAttribute("method", method.ToString().ToLowerInvariant()); var context = new TagHelperContext( allAttributes: new TagHelperAttributeList(new[] { expectedAttribute }), items: new Dictionary<object, object>(), uniqueId: "test"); var output = new TagHelperOutput( "form", attributes: new TagHelperAttributeList(), getChildContentAsync: (useCachedResult, encoder) => { var tagHelperContent = new DefaultTagHelperContent(); tagHelperContent.SetContent("Something"); return Task.FromResult<TagHelperContent>(tagHelperContent); }); var generator = new Mock<IHtmlGenerator>(MockBehavior.Strict); generator .Setup(mock => mock.GenerateForm( It.IsAny<ViewContext>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<object>(), It.IsAny<string>(), It.IsAny<object>())) .Returns(new TagBuilder("form")); generator.Setup(mock => mock.GenerateAntiforgery(viewContext)) .Returns(new HtmlString("<input />")); var formTagHelper = new FormTagHelper(generator.Object) { Action = "Index", Antiforgery = antiforgery, ViewContext = viewContext, Method = method.ToString().ToLowerInvariant() }; // Act await formTagHelper.ProcessAsync(context, output); // Assert Assert.Equal("form", output.TagName); Assert.Equal(TagMode.StartTagAndEndTag, output.TagMode); var attribute = Assert.Single(output.Attributes); Assert.Equal(expectedAttribute, attribute); Assert.Empty(output.PreContent.GetContent()); Assert.True(output.Content.GetContent().Length == 0); Assert.Equal(expectedPostContent, output.PostContent.GetContent()); }
public void BeginRouteForm_RendersExpectedValues( string routeName, object routeValues, FormMethod method, object htmlAttributes) { // Arrange var expectedAction = "http://localhost/Hello/World"; var expectedStartTag = string.Format( "<form action=\"HtmlEncode[[{0}]]\" method=\"HtmlEncode[[{1}]]\"{2}>", expectedAction, method.ToString().ToLowerInvariant(), GetHtmlAttributesAsString(htmlAttributes)); var urlHelper = new Mock<IUrlHelper>(MockBehavior.Strict); urlHelper .Setup(realHelper => realHelper.RouteUrl(It.Is<UrlRouteContext>(context => string.Equals(context.RouteName, routeName) && context.Values == routeValues && context.Protocol == null && context.Host == null && context.Fragment == null))) .Returns(expectedAction) .Verifiable(); var htmlHelper = DefaultTemplatesUtilities.GetHtmlHelper(urlHelper.Object); // Guards Assert.NotNull(htmlHelper.ViewContext); var writer = Assert.IsAssignableFrom<StringWriter>(htmlHelper.ViewContext.Writer); var builder = writer.GetStringBuilder(); Assert.NotNull(builder); // Act var mvcForm = htmlHelper.BeginRouteForm(routeName, routeValues, method, htmlAttributes); // Assert Assert.NotNull(mvcForm); Assert.Equal(expectedStartTag, builder.ToString()); urlHelper.Verify(); }
public void BeginRouteFormWithRouteNameRouteValuesAndMethodParameters_CallsHtmlGeneratorWithExpectedValues( string routeName, object routeValues, FormMethod method) { // Arrange var tagBuilder = new TagBuilder(tagName: "form", htmlEncoder: new NullTestEncoder()); var htmlGenerator = new Mock<IHtmlGenerator>(MockBehavior.Strict); var htmlHelper = DefaultTemplatesUtilities.GetHtmlHelper(htmlGenerator.Object); htmlGenerator .Setup(realHelper => realHelper.GenerateRouteForm( htmlHelper.ViewContext, routeName, routeValues, method.ToString().ToLowerInvariant(), null)) // htmlAttributes .Returns(tagBuilder) .Verifiable(); // Guards Assert.NotNull(htmlHelper.ViewContext); var writer = Assert.IsAssignableFrom<StringWriter>(htmlHelper.ViewContext.Writer); var builder = writer.GetStringBuilder(); Assert.NotNull(builder); // Act var mvcForm = htmlHelper.BeginRouteForm(routeName, routeValues, method); // Assert Assert.NotNull(mvcForm); Assert.Equal("<form>", builder.ToString()); htmlGenerator.Verify(); }
public override string GetStringAttributes() { if (string.IsNullOrWhiteSpace(CacheAttributes)) { if (FormMethod != null) { SetAttribute("method", FormMethod.ToString()); } else { RemoveAttribute("method"); } if (EncTypeData != null) { SetAttribute("enctype", GetEnctypeHtmlForm(EncTypeData)); } else { RemoveAttribute("enctype"); } if (!string.IsNullOrWhiteSpace(FormAction)) { SetAttribute("action", FormAction); } else { RemoveAttribute("action"); } if (!string.IsNullOrWhiteSpace(AcceptCharset)) { SetAttribute("accept-charset", AcceptCharset); } else { RemoveAttribute("accept-charset"); } if (FormTarget != hmFormTargetsEnum.NULL) { SetAttribute("target", FormTarget.ToString("g")); } else { RemoveAttribute("target"); } if (NoValidate) { SetAttribute("novalidate", null); } else { RemoveAttribute("novalidate"); } if (!(AutoComplete is null)) { SetAttribute("autocomplete", AutoComplete == true ? "on" : "off"); } else { RemoveAttribute("autocomplete"); } }
public TypeaheadAjax Method(FormMethod value) { Attributes["method"] = string.Format("'{0}'", value.ToString()); return(this); }
public static async Task <IHtmlContent> GenerateFormAsync <TModel>(this IHtmlHelper html, HttpContext context, string url, FormMethod method, TModel model, object htmlAttributes = default, Func <TModel, IHtmlContent> appendHtmlContent = default, bool?antiforgery = default, string globalCssClass = "form-control") { var type = typeof(TModel); var serviceProvider = context.RequestServices; var options = serviceProvider.GetRequiredService <AutoGenerateFormBuilder>(); var properties = ControlAttributes.GetOrAdd(type, t => new FormProperties(t).Properties); var form = new TagBuilder("form"); form.MergeAttribute("method", method.ToString()); form.MergeAttribute("action", url); var attribute = htmlAttributes.GetAttributeFromObject(); if (attribute != null) { form.MergeAttributes(attribute, true); } var hasUploader = false; var hasEditor = false; var uploaderScripts = new StringBuilder(); var editorScripts = new StringBuilder(); foreach (var prop in properties) { var name = prop.PropertyInfo.Name; var value = model == null ? null : prop.PropertyInfo.GetValue(model); if (prop.DataListColumnConvert != null) { value = prop.DataListColumnConvert.Convert(value); } var itemType = prop.PropertyInfo.PropertyType; var group = new TagBuilder("div"); group.MergeAttribute("class", "form-group"); if (prop.Hide) { group.MergeAttribute("style", "display:none"); } var groupName = new TagBuilder("label"); groupName.InnerHtml.AppendHtml(prop.DisplayName); if (prop.PropertyInfo.GetCustomAttribute <RequiredAttribute>() != null) { groupName.InnerHtml.AppendHtml("<span style='color:red;font-weight:bold;'> * </span>"); } group.InnerHtml.AppendHtml(groupName); var controlContainer = new TagBuilder("div"); controlContainer.AddCssClass($"control-group {name.ToLower()}-control-group"); foreach (var control in prop.Controls) { switch (control.ControlType) { case HtmlControlType.Label: controlContainer.InnerHtml.AppendHtml(html.ExLabel(name, value, control.GetAttributes(), globalCssClass)); break; case HtmlControlType.Hidden: controlContainer.InnerHtml.AppendHtml(html.ExHidden(name, value, control.GetAttributes())); break; case HtmlControlType.TextBox: controlContainer.InnerHtml.AppendHtml(html.ExTextBox(name, value, control.GetAttributes(), globalCssClass)); break; case HtmlControlType.Password: controlContainer.InnerHtml.AppendHtml(html.ExPassword(name, value, control.GetAttributes(), globalCssClass)); break; case HtmlControlType.TextArea: controlContainer.InnerHtml.AppendHtml(html.ExTextArea(name, value, control.GetAttributes(), globalCssClass)); break; case HtmlControlType.DropDownList: var dropDownAttr = (DropDownListAttribute)control; var dropDownDataSource = (IDataSource)serviceProvider.GetService(dropDownAttr.DataSource); if (dropDownDataSource == null) { controlContainer.MergeAttribute("style", "color:red;"); controlContainer.InnerHtml.AppendHtml("Please bind the data source."); break; } controlContainer.InnerHtml.AppendHtml(html.ExDropDownList(name, await dropDownDataSource.GetAsync(value == null ? null : new[] { value }), dropDownAttr.OptionLabel, control.GetAttributes(), globalCssClass)); break; case HtmlControlType.ListBox: var listBoxAttr = (ListBoxAttribute)control; var listBoxDataSource = (IDataSource)serviceProvider.GetService(listBoxAttr.DataSource); if (listBoxDataSource == null) { controlContainer.MergeAttribute("style", "color:red;"); controlContainer.InnerHtml.AppendHtml("Please bind the data source."); break; } if (typeof(IList).IsAssignableFrom(itemType)) { controlContainer.InnerHtml.AppendHtml(html.ExListBox(name, await listBoxDataSource.GetAsync(((IList)value).Cast <object>()), listBoxAttr.OptionLabel, control.GetAttributes(), globalCssClass)); } else { controlContainer.MergeAttribute("style", "color:red;"); controlContainer.InnerHtml.AppendHtml($"ListBox does not support type {itemType}."); } break; case HtmlControlType.RadioButton: var radioButtonAttr = (RadioButtonAttribute)control; var radioButtonDataSource = (IDataSource)serviceProvider.GetService(radioButtonAttr.DataSource); if (radioButtonDataSource == null) { controlContainer.MergeAttribute("style", "color:red;"); controlContainer.InnerHtml.AppendHtml("Please bind the data source."); break; } controlContainer.InnerHtml.AppendHtml(html.ExRadioButton(name, await radioButtonDataSource.GetAsync(value == null ? null : new[] { value }), radioButtonAttr.GetAttributes(), globalCssClass)); break; case HtmlControlType.CheckBox: var checkBoxAttr = (CheckBoxAttribute)control; if (typeof(IList).IsAssignableFrom(itemType)) { var checkBoxDataSource = (IDataSource)serviceProvider.GetService(checkBoxAttr.DataSource); if (checkBoxDataSource == null) { controlContainer.MergeAttribute("style", "color:red;"); controlContainer.InnerHtml.AppendHtml("Please bind the data source."); break; } controlContainer.InnerHtml.AppendHtml(html.ExCheckBox(name, await checkBoxDataSource.GetAsync(((IList)value).Cast <object>()), checkBoxAttr.GetAttributes(), globalCssClass)); } else if (typeof(bool).IsAssignableFrom(itemType)) { controlContainer.InnerHtml.AppendHtml(html.ExSingleCheckBox(name, value != null && bool.Parse(value?.ToString()), checkBoxAttr.GetAttributes(), globalCssClass)); } else { controlContainer.MergeAttribute("style", "color:red;"); controlContainer.InnerHtml.AppendHtml($"CheckBox does not support type {itemType}."); } break; case HtmlControlType.Button: var buttonAttr = (ButtonAttribute)control; controlContainer.InnerHtml.AppendHtml(html.Button(buttonAttr.ButtonText, buttonAttr.GetAttributes(), globalCssClass)); break; case HtmlControlType.File: controlContainer.InnerHtml.AppendHtml(html.ExFile(name, control.GetAttributes(), globalCssClass)); break; case HtmlControlType.RichEditor: var editorAttr = (RichEditorAttribute)control; var editorPartialName = string.IsNullOrWhiteSpace(editorAttr.PartialName) ? options.RichEditorOptions.PartialName : editorAttr.PartialName; controlContainer.InnerHtml.AppendHtml(await html.ExRichEditor(name, value?.ToString(), editorPartialName, editorAttr.GetAttributes())); if (string.IsNullOrWhiteSpace(editorPartialName)) { var editorOptions = string.IsNullOrWhiteSpace(editorAttr.Options) ? JsonConvert.SerializeObject(options.RichEditorOptions.Options, Formatting.None) : editorAttr.Options; editorScripts.AppendFormat("ClassicEditor.create(document.querySelector(\"#{0}\"),{1}).catch(function(err){{alert(err)}}),", name, editorOptions); if (!hasEditor) { hasEditor = true; } } break; case HtmlControlType.Uploader: var uploaderAttr = (UploaderAttribute)control; var uploaderPartialName = string.IsNullOrWhiteSpace(uploaderAttr.PartialName) ? options.UploaderOptions.PartialName : uploaderAttr.PartialName; var global = options.UploaderOptions; JToken uploaderOptions = null; //if (string.IsNullOrWhiteSpace(uploaderPartialName)) //{ //合并参数 uploaderOptions = new JObject(); if (value != null) { uploaderOptions["data"] = JToken.FromObject(value); } var fileBaseUrl = ChooseOptionString(global.FileBaseUrl, uploaderAttr.FileBaseUrl); if (!string.IsNullOrWhiteSpace(fileBaseUrl)) { uploaderOptions["fileBaseUrl"] = fileBaseUrl; } var auto = ChooseOptionEnum(global.AutoUpload, uploaderAttr.AutoUpload); if (auto) { uploaderOptions["auto"] = auto; } var serverUrl = ChooseOptionString(global.ServerUrl, uploaderAttr.ServerUrl); if (serverUrl != DefaultOptionValue.ServerUrl) { uploaderOptions["serverUrl"] = serverUrl; } if (ChooseOptionEnum(global.Multiple, uploaderAttr.Multiple)) { uploaderOptions["multiple"] = true; } #region Chunked if (ChooseOptionEnum(global.Chunked.Enable, uploaderAttr.Chunked)) { JToken chunk = new JObject { ["chunked"] = true }; var chunkSize = ChooseOptionInt(global.Chunked.ChunkSize, uploaderAttr.ChunkSize); if (chunkSize != DefaultOptionValue.ChunkSize) { chunk["chunkSize"] = chunkSize; } var checkUrl = ChooseOptionString(global.Chunked.ChunkCheckServerUrl, uploaderAttr.ChunkCheckServerUrl); if (checkUrl != DefaultOptionValue.ChunkCheckServerUrl) { chunk["chunkCheckServerUrl"] = checkUrl; } var mergeUrl = ChooseOptionString(global.Chunked.ChunkMergeServerUrl, uploaderAttr.ChunkMergeServerUrl); if (mergeUrl != DefaultOptionValue.ChunkMergeServerUrl) { chunk["chunkMergeServerUrl"] = mergeUrl; } uploaderOptions["chunk"] = chunk; } #endregion #region Accept JToken accept = null; //var acceptTitle = ChooseOptionString(global.Accept.Title, uploaderAttr.AcceptTitle); //if (acceptTitle != DefaultOptionValue.AcceptTitle) //{ // accept ??= new JObject(); // accept["title"] = acceptTitle; //} var acceptExtensions = ChooseOptionString(global.Accept.Extensions, uploaderAttr.AcceptExtensions); if (acceptExtensions != DefaultOptionValue.AcceptExtensions) { accept ??= new JObject(); accept["extensions"] = acceptExtensions; } var acceptMineTypes = ChooseOptionString(global.Accept.MimeTypes, uploaderAttr.AcceptMimeTypes); if (acceptMineTypes != DefaultOptionValue.AcceptMimeTypes) { accept ??= new JObject(); accept["mimeTypes"] = acceptMineTypes; } if (accept != null) { uploaderOptions["accept"] = accept; } #endregion #region Translation JToken translation = null; var uploadBtnText = ChooseOptionString(global.Translation.UploadBtnText, uploaderAttr.UploadBtnText); if (uploadBtnText != DefaultOptionValue.UploadBtnText) { translation ??= new JObject(); translation["uploadBtnText"] = uploadBtnText; } var addBtnText = ChooseOptionString(global.Translation.AddFileBtnText, uploaderAttr.AddFileBtnText); if (addBtnText != DefaultOptionValue.AddFileBtnText) { translation ??= new JObject(); translation["addFileBtnText"] = addBtnText; } var pauseBtnText = ChooseOptionString(global.Translation.PauseBtnText, uploaderAttr.PauseBtnText); if (pauseBtnText != DefaultOptionValue.PauseBtnText) { translation ??= new JObject(); translation["pauseBtnText"] = pauseBtnText; } var continueBtnText = ChooseOptionString(global.Translation.ContinueBtnText, uploaderAttr.ContinueBtnText); if (continueBtnText != DefaultOptionValue.ContinueBtnText) { translation ??= new JObject(); translation["continueBtnText"] = continueBtnText; } var exceedFileNumLimitAlert = ChooseOptionString(global.Translation.ExceedFileNumLimitAlert, uploaderAttr.ExceedFileNumLimitAlert); if (exceedFileNumLimitAlert != DefaultOptionValue.ExceedFileNumLimitAlert) { translation["ExceedFileNumLimitAlert"] = exceedFileNumLimitAlert; } var exceedFileSizeLimitAlert = ChooseOptionString(global.Translation.ExceedFileSizeLimitAlert, uploaderAttr.ExceedFileSizeLimitAlert); if (exceedFileSizeLimitAlert != DefaultOptionValue.ExceedFileSizeLimitAlert) { translation["ExceedFileSizeLimitAlert"] = exceedFileSizeLimitAlert; } if (translation != null) { uploaderOptions["translation"] = translation; } #endregion #region Compress var enableCompress = ChooseOptionEnum(global.Compress.Enable, uploaderAttr.EnableCompress); if (enableCompress) { JToken compress = new JObject(); var width = ChooseOptionInt(global.Compress.Width, uploaderAttr.CompressWidth); if (width != DefaultOptionValue.CompressWidth) { compress["width"] = width; } var height = ChooseOptionInt(global.Compress.Height, uploaderAttr.CompressHeight); if (height != DefaultOptionValue.CompressHeight) { compress["height"] = height; } var quality = ChooseOptionInt(global.Compress.Quality, uploaderAttr.CompressQuality); if (quality != DefaultOptionValue.CompressQuality) { compress["quality"] = quality; } var crop = ChooseOptionEnum(global.Compress.Crop, uploaderAttr.CompressCrop); if (crop) { compress["crop"] = crop; } var preserveHeaders = ChooseOptionEnum(global.Compress.PreserveHeaders, uploaderAttr.CompressPreserveHeaders); if (!preserveHeaders) { compress["preserveHeaders"] = preserveHeaders; } var noCompressIfLarger = ChooseOptionEnum(global.Compress.NoCompressIfLarger, uploaderAttr.CompressNoCompressIfLarger); if (noCompressIfLarger) { compress["noCompressIfLarger"] = noCompressIfLarger; } var compressSize = ChooseOptionInt(global.Compress.CompressSize, uploaderAttr.CompressSize); if (compressSize != 0) { compress["compressSize"] = compressSize; } uploaderOptions["compress"] = compress; } #endregion #region FormData if (uploaderAttr.FormData != null || global.FormData != null) { uploaderOptions["formData"] = JObject.FromObject(uploaderAttr.FormData ?? global.FormData); } #endregion #region FileNumLimit var fileNumLimit = ChooseOptionInt(global.FileNumLimit, uploaderAttr.FileNumLimit); if (fileNumLimit != DefaultOptionValue.FileNumLimit) { uploaderOptions["fileNumLimit"] = fileNumLimit; } #endregion #region FileSingleSizeLimit var fileSingleSizeLimit = ChooseOptionInt(global.FileSingleSizeLimit, uploaderAttr.FileSingleSizeLimit); if (fileSingleSizeLimit != DefaultOptionValue.FileSingleSizeLimit) { uploaderOptions["fileSingleSizeLimit"] = fileSingleSizeLimit; } #endregion #region Threads var threads = ChooseOptionInt(global.Threads, uploaderAttr.Threads); if (threads != DefaultOptionValue.Threads) { uploaderOptions["threads"] = threads; } #endregion #region Thumb JToken thumb = null; var thumbWidth = ChooseOptionInt(global.Thumb.Width, uploaderAttr.ThumbWidth); if (thumbWidth != DefaultOptionValue.ThumbWidth) { thumb ??= new JObject(); thumb["width"] = thumbWidth; } var thumbHeight = ChooseOptionInt(global.Thumb.Height, uploaderAttr.ThumbHeight); if (thumbHeight != DefaultOptionValue.ThumbHeight) { thumb ??= new JObject(); thumb["height"] = thumbHeight; } var thumbQuality = ChooseOptionInt(global.Thumb.Quality, uploaderAttr.ThumbQuality); if (thumbQuality != DefaultOptionValue.ThumbQuality) { thumb ??= new JObject(); thumb["quality"] = thumbQuality; } var allowMagnify = ChooseOptionEnum(global.Thumb.AllowMagnify, uploaderAttr.ThumbAllowMagnify); if (allowMagnify) { thumb ??= new JObject(); thumb["allowMagnify"] = allowMagnify; } var thumbCrop = ChooseOptionEnum(global.Thumb.Crop, uploaderAttr.ThumbCrop); if (!thumbCrop) { thumb ??= new JObject(); thumb["crop"] = thumbCrop; } if (thumb != null) { uploaderOptions["thumb"] = thumb; } #endregion uploaderOptions["storeProvider"] = global.StoreProvider.ToString(); //} var tips = ChooseOptionString(global.Translation.Tips, uploaderAttr.Tips); controlContainer.InnerHtml.AppendHtml(await html.Uploader(name, value, uploaderPartialName, uploaderAttr.GetAttributes(), new Dictionary <string, string> { { "Tips", tips }, { "UploadBtnText", ChooseOptionString(global.Translation.UploadBtnText, uploaderAttr.UploadBtnText) }, { "auto", uploaderOptions["auto"]?.ToObject <string>() } })); if (string.IsNullOrWhiteSpace(uploaderPartialName)) { uploaderScripts.AppendFormat("uploader_{0}=$(\"#{0}-container\").InitUploader({1}),", name, uploaderOptions.ToString(Formatting.None)); if (!hasUploader) { hasUploader = true; } } break; } } group.InnerHtml.AppendHtml(controlContainer); group.InnerHtml.AppendHtml(html.ValidationMessage(name)); form.InnerHtml.AppendHtml(group); } if (appendHtmlContent != null) { form.InnerHtml.AppendHtml(appendHtmlContent(model)); } if (antiforgery.HasValue && antiforgery.Value) { form.InnerHtml.AppendHtml(html.AntiForgeryToken()); } if (hasUploader || hasEditor) { var script = new TagBuilder("script"); var scriptString = "document.addEventListener(\"DOMContentLoaded\",function(){if(" + hasUploader.ToString().ToLower() + "){var e=document.querySelectorAll(\".uploader-container\");if(!window.jQuery)return void e.forEach(function(e,t){e.innerHTML=\'<label style=\"color:red;\">Please install jQuery first.</label>\'});if(!window.WebUploader)return void e.forEach(function(e,t){e.innerHTML=\'<label style=\"color:red;\">Please install WebUploader first.</label>\'});var t=document.createElement(\"link\");t.setAttribute(\"rel\",\"stylesheet\"),t.setAttribute(\"href\",\"/auto-generate-html-control/resources/css/uploader.min.css\"),document.querySelector(\"header\").appendChild(t);var r=document.createElement(\"script\");r.setAttribute(\"src\",\"/auto-generate-html-control/resources/js/uploader.min.js\"),r.addEventListener(\"load\",function(){if(window.OnUploaderJsReady)OnUploaderJsReady();" + uploaderScripts.ToString().TrimEnd(',') + "}),document.querySelector(\"body\").appendChild(r)}" + hasEditor.ToString().ToLower() + "&&(window.ClassicEditor?(" + (hasEditor ? editorScripts.ToString().TrimEnd(',') : "a=0") + "):document.querySelectorAll(\".editor-container\").forEach(function(e,t){e.innerHTML=\'<label style=\"color:red;\">Please install CKEditor5 first.</label>\'}))});"; script.InnerHtml.AppendHtml(scriptString); form.InnerHtml.AppendHtml(script); } return(form); }
/// <summary> /// Set the 'formmethod' attribute. /// </summary> /// <param name="value">The value of the attribute.</param> public T Method(FormMethod value) { Attr(HtmlAttribute.FormMethod, value.ToString().ToLower()); return((T)this); }
public void BeginFormWithMethodAndHtmlAttributesParameters_SuppressAntiforgery_CallsHtmlGeneratorWithExpectedValues( FormMethod method, object htmlAttributes) { // Arrange var tagBuilder = new TagBuilder(tagName: "form"); var htmlGenerator = new Mock<IHtmlGenerator>(MockBehavior.Strict); var htmlHelper = DefaultTemplatesUtilities.GetHtmlHelper(htmlGenerator.Object); htmlGenerator .Setup(g => g.GenerateForm( htmlHelper.ViewContext, null, // actionName null, // controllerName null, // routeValues method.ToString().ToLowerInvariant(), htmlAttributes)) .Returns(tagBuilder) .Verifiable(); // Guards Assert.NotNull(htmlHelper.ViewContext); var writer = Assert.IsAssignableFrom<StringWriter>(htmlHelper.ViewContext.Writer); var builder = writer.GetStringBuilder(); Assert.NotNull(builder); // Act var mvcForm = htmlHelper.BeginForm(method, antiforgery: false, htmlAttributes: htmlAttributes); // Assert Assert.NotNull(mvcForm); Assert.Equal("<form>", builder.ToString()); htmlGenerator.Verify(); }
public static String PackFormMethod(FormMethod formMethod) { return "method=\"" + formMethod.ToString() + "\""; }
public void BeginRouteFormWithRouteNameMethodAndHtmlAttributesParameters_CallsHtmlGeneratorWithExpectedValues( string routeName, FormMethod method, object htmlAttributes) { // Arrange var tagBuilder = new TagBuilder(tagName: "form"); var htmlGenerator = new Mock<IHtmlGenerator>(MockBehavior.Strict); var htmlHelper = DefaultTemplatesUtilities.GetHtmlHelper(htmlGenerator.Object); htmlGenerator .Setup(g => g.GenerateRouteForm( htmlHelper.ViewContext, routeName, null, // routeValues method.ToString().ToLowerInvariant(), htmlAttributes)) .Returns(tagBuilder) .Verifiable(); if (method != FormMethod.Get) { htmlGenerator .Setup(g => g.GenerateAntiforgery(htmlHelper.ViewContext)) .Returns(HtmlString.Empty) .Verifiable(); } // Guards Assert.NotNull(htmlHelper.ViewContext); var writer = Assert.IsAssignableFrom<StringWriter>(htmlHelper.ViewContext.Writer); var builder = writer.GetStringBuilder(); Assert.NotNull(builder); // Act var mvcForm = htmlHelper.BeginRouteForm(routeName, method, htmlAttributes); // Assert Assert.NotNull(mvcForm); Assert.Equal("<form>", builder.ToString()); htmlGenerator.Verify(); }
public void BeginFormWithActionNameContollerNameRouteValuesAndMethodParameters_CallsHtmlGeneratorWithExpectedValues( string actionName, string controllerName, object routeValues, FormMethod method) { // Arrange var tagBuilder = new TagBuilder(tagName: "form"); var htmlGenerator = new Mock<IHtmlGenerator>(MockBehavior.Strict); var htmlHelper = DefaultTemplatesUtilities.GetHtmlHelper(htmlGenerator.Object); htmlGenerator .Setup(g => g.GenerateForm( htmlHelper.ViewContext, actionName, controllerName, routeValues, method.ToString().ToLowerInvariant(), null)) // htmlAttributes .Returns(tagBuilder) .Verifiable(); htmlGenerator .Setup(g => g.GenerateAntiforgery(htmlHelper.ViewContext)) .Returns(HtmlString.Empty) .Verifiable(); // Guards Assert.NotNull(htmlHelper.ViewContext); var writer = Assert.IsAssignableFrom<StringWriter>(htmlHelper.ViewContext.Writer); var builder = writer.GetStringBuilder(); Assert.NotNull(builder); // Act var mvcForm = htmlHelper.BeginForm(actionName, controllerName, routeValues, method); // Assert Assert.NotNull(mvcForm); Assert.Equal("<form>", builder.ToString()); htmlGenerator.Verify(); }
private IAsyncResult BeginGetResponse(AsyncCallback callback) { StringBuilder serviceUri = new StringBuilder(); HttpWebRequest serviceRequest = null; ++kNumberOfServicesCalled; if (mMethod == FormMethod.POST) { string boundary = Guid.NewGuid().ToString().Replace("-", ""); MemoryStream postData = GetPostData(boundary); byte[] byteData = new byte[postData.Length]; postData.Read(byteData, 0, (int)postData.Length); postData.Close(); serviceRequest = (HttpWebRequest)WebRequest.Create(mServiceUrl); serviceRequest.ContentType = "multipart/form-data; boundary=" + boundary; serviceRequest.Method = mMethod.ToString(); serviceRequest.ContentLength = byteData.Length; Stream serviceStreamWriter = serviceRequest.GetRequestStream(); serviceStreamWriter.Write(byteData, 0, byteData.Length); serviceStreamWriter.Close(); } else { serviceUri.Append(mServiceUrl); if (mEncrypted) { serviceUri.Append("?encrypted=true"); } else { serviceUri.Append("?encrypted=false"); } foreach (KeyValuePair <string, string> param in mStringParams) { serviceUri.AppendFormat("&{0}={1}", param.Key, param.Value); } mServiceUrl = serviceUri.ToString(); serviceRequest = (HttpWebRequest)WebRequest.Create(mServiceUrl); serviceRequest.Method = mMethod.ToString(); serviceRequest.ContentType = "text/xml;"; } System.Threading.Interlocked.Increment(ref mPendingRequests); mLogger.InfoFormat("Num pending requests ({0}), starting: {1} ", mPendingRequests, mServiceUrl); int numWorker, numIOCP; System.Threading.ThreadPool.GetAvailableThreads(out numWorker, out numIOCP); mLogger.InfoFormat("Available threads: " + numWorker + ", " + numIOCP); IAsyncResult res = serviceRequest.BeginGetResponse(callback, serviceRequest); // Managing our own timeout because async requests don't obey HttpWebRequest.Timeout ThreadPool.RegisterWaitForSingleObject(res.AsyncWaitHandle, TimeoutCallback, new TimeoutState(res, serviceRequest, callback), mTimeout, true); return(res); }
public static MvcHtmlString Button(this HtmlHelper helper, string text, string urlAction, FormMethod method, object htmlAttributes) { var tagBuilder = new TagBuilder("input"); FillWithAttributes(tagBuilder, new { type = "submit", formaction = urlAction, formmethod = method.ToString(), value = text }); FillWithAttributes(tagBuilder, htmlAttributes); return(new MvcHtmlString(tagBuilder.ToString())); }