Required in html helper

How to add «required» attribute to mvc razor viewmodel text input editor

I need this field to be required (i.e. have a red outline when user navigates out without putting a value inn). In a WebForms HTML 5 I could just say to have this effect. What is the proper syntax to accomplish this in a Razor syntax?

Protip: The @ on @placeholder is not needed. It’s only needed when the name is a keyword like class .

5 Answers 5

You can use the required html attribute if you want:

@Html.TextBoxFor(m => m.ShortName, new < @class = "form-control", placeholder = "short name", required="required">) 

or you can use the RequiredAttribute class in .Net. With jQuery the RequiredAttribute can Validate on the front end and server side. If you want to go the MVC route, I’d suggest reading Data annotations MVC3 Required attribute.

You can get really advanced:

@< // if you aren't using UnobtrusiveValidation, don't pass anything to this constructor var attributes = new Dictionary( Html.GetUnobtrusiveValidationAttributes(ViewData.TemplateInfo.HtmlFieldPrefix)); attributes.Add("class", "form-control"); attributes.Add("placeholder", "short name"); if (ViewData.ModelMetadata.ContainerType .GetProperty(ViewData.ModelMetadata.PropertyName) .GetCustomAttributes(typeof(RequiredAttribute), true) .Select(a => a as RequiredAttribute) .Any(a => a != null)) < attributes.Add("required", "required"); >@Html.TextBoxFor(m => m.ShortName, attributes) > 

or if you need it for multiple editor templates:

public static class ViewPageExtensions < public static IDictionaryGetAttributes(this WebViewPage instance) < // if you aren't using UnobtrusiveValidation, don't pass anything to this constructor var attributes = new Dictionary( instance.Html.GetUnobtrusiveValidationAttributes( instance.ViewData.TemplateInfo.HtmlFieldPrefix)); if (ViewData.ModelMetadata.ContainerType .GetProperty(ViewData.ModelMetadata.PropertyName) .GetCustomAttributes(typeof(RequiredAttribute), true) .Select(a => a as RequiredAttribute) .Any(a => a != null)) < attributes.Add("required", "required"); >> > 

Update 1 (for Tomas who is unfamilar with ViewData).

So basically it (ViewBag) replaces magic strings:

Источник

Make Yii2 HTML Helper Input Required: A Rephrased Title

The inquiry is regarding a form generated with HTML helper. The question is whether it’s possible to mark form fields as necessary and prevent the form from submitting if it’s empty, similar to the functionality of ActiveForm. However, since ActiveForm can’t be used for some reason, the solution is to use a JS library instead. It’s important to note that the HTML provided below won’t work in IE. The answer is that there are numerous polyfills available for HTML5 forms.

Yii2 HTML helper input make required

I possess a form created using the HTML helper.

 
'control-label']); ?> 50, 'class'=>'form-control']) ?>
'control-label']); ?> 100, 'class'=>'form-control']) ?>

Is it possible to prevent empty submissions of form fields required and prevent form without using ActiveForm? Alternatively, can a JavaScript library be utilized for this purpose?

Consider implementing a formmodel that inherits from the Model class. This approach will enable you to manage all the required validations.

This is the only code that is effective, specifically for a div that has the required class.

How can I create a Html Helper like Html.BeginForm, I have an Extension Method that verifies if the user is able to see a portion of the webpage, based on a Role. If I simple remove the content, this brings me more work as all the missing forms will not be correctly registered upon save and I have to deal with this behavior by modifying all my code, so I thought why …

How can I create a Html Helper like Html.BeginForm

I’ve created an Extension Method that checks whether a user has access to a specific section of a webpage based on their assigned Role.

Eliminating the content would entail additional work for me since the absent forms will not be accurately recorded upon saving, leading me to modify my code to rectify this issue. Therefore, instead of taking that route, I pondered why not utilize the display:none; attribute?

I’m interested in getting something similar to:

@using(Html.RoleAccess(currentUser, RoleAccessType.Content_General_Website))

and this would result in the creation of some written content that looks like:

If the user is authorized, they can make use of display:block; .

I am able to generate a basic HtmlHelper , but I’m unsure about how to produce an output that includes the

conclusion.

public static string RoleAccess( this HtmlHelper helper, UserInfo user, RoleAccessType role) < return String.Format( "
", role.ToString(), user.HasAccess(role)); >
public static class HtmlExtensions < private class RoleContainer : IDisposable < private readonly TextWriter _writer; public RoleContainer(TextWriter writer) < _writer = writer; >public void Dispose() < _writer.Write("

and then you can use it like this:

@using(Html.RoleAccess("Administrator"))

The helper's arguments can be adjusted to suit your needs.

public static IDisposable RoleAccess( this HtmlHelper helper, UserInfo user, RoleAccessType role ) < var style = "display:none;"; if (user.HasAccess(role)) < style = "display:block;"; >var writer = htmlHelper.ViewContext.Writer; writer.WriteLine("
"); return new RoleContainer(writer); >

Set required attribute on Html.Textbox, Try. new < required = string.Empty>As an aside, according to the W3C docs, required is a Boolean attribute, and I quote: The presence of a boolean attribute on an element represents the true value, and the absence of the attribute represents the false value.

Making required property work in html forms in ie

Do you know of a solution to make the required property of forms compatible with IE 6+? I have successfully tested it on Chrome and Firefox. Unfortunately, the HTML code I have tried doesn't work on IE. I would prefer not to use any scripts, but I am open to an easy solution if you have one.

Numerous polyfills are available for HTML5 forms, such as the jQuery form shim. Prior to making a decision, it is recommended to test the various alternatives to see how they report errors, such as when a required field is missing, as the reporting style may differ.

Rendering a Form in ASP.NET MVC Using HTML Helpers, The BeginForm helper marks the start of an HTML form and renders as an HTML form element. The BeginForm helper method has several overrides. The version of the BeginForm helper shown in the following example takes two parameters, the names of the action method and the controller to submit the …

Источник

Set required attribute on Html.Textbox

However, required = "required" clearly doesn't return just required . So, my question is, is there any way I can force it to return required like in the first example above when using Html.Textbox?

I am aware of this, though as it did not yield the same functionality as twitter.github.com/bootstrap/base-css.html#forms, I thought that it may be prudent to try to use it the same way to see if that resolved it.

This is not invalid HTML as per the HTML5 specification. The correct syntax is only required. w3.org/html/wg/drafts/html/master/…

4 Answers 4

i think you should use like this

 @Html.TextBoxFor(model => model.Name, new < @class = "text", type = "email", required = "required" >) 

i think this will help you.

How did this answer the question? Does this not render required="required" ? Personally, Im working on accessibility problems and even though required="required" is valid syntax, for screen readers I'm under the impression it is best to have required by itself.

As an aside, according to the W3C docs, required is a Boolean attribute, and I quote:

The presence of a boolean attribute on an element represents the true value, and the absence of the attribute represents the false value. If the attribute is present, its value must either be the empty string or a value that is an ASCII case-insensitive match for the attribute's canonical name, with no leading or trailing whitespace.

required required="required" required="" 

You seem to have applied a different class to the textbox: input-xlarge , whereas in your desired markup it's called span3 .

@Html.TextBox( "CustomerEmail", null, new < @class = "span3", type = "email", required = "required" >) 

As far as the required part is concerned, the correct syntax here is required="required" , otherwise you simply get broken HTML.

I know this. The example I provided from my code contains the class I wish to use and is therefore correct and that wasn't my question. In addition to this, required can be set in a number of ways though i am looking to replicate the way it has been set in the Bootstrap documentation to see if it yields the same result.

This helper will generate semantically identical code to what you have shown as desired output. So I guess what you have shown as desired markup is not that much desired as it doesn't work quite well. Anyway this has strictly nothing to do with ASP.NET MVC. I guess you have some problem with the styles, .

No, I have referred merely to the "required" portion of the example I provided as the attribute is the desired output.

required and required="required" are strictly identical, except that the first is incorrect and broken HTML but client browsers understand it. Anyway you simply cannot force an HTML helper such as TextBox to generate broken HTML. It's not how HTML helpers were designed. If you want to generated broken HTML you will have to do it by hand or write a custom HTML helper. I am afraid that ASP.NET MVC cannot help you here.

Again, the first is not incorrect nor broken, it is the latter that is incorrect. The presence alone of boolean attribute in the HTML5 specification means true, while the absence of the attribute means false. w3.org/html/wg/drafts/html/master/…

Источник

Читайте также:  Программный код калькулятора html
Оцените статью