label or #html.Label ASP.net MVC 4 - razor

Newbie to ASP.net MVC 4 and trying to make sense of Razor. If I wanted to just display some text in my .cshtml page, can I use
<label class="LabelCSSTop">Introduction</label>
or should I use:
#Html.Label("STW", htmlAttributes: new { #class = "LabelCSSTop" })
Not sure if one is preferred over the other or if either is okay. If the latter emits the label tag anyway, should I just stick to the former?
Again, if I just wanted to display a text box, can I just do this:
<input id="txtName" type="text" />
or should I do this:
#Html.TextBox("txtName", "")
Is there a situation when I should use the #Html over the regular html tag?
Thanks in advance!!

In the case of your label snippet, it doesn't really matter. I would go for the simpler syntax (plain HTML).
Most helper methods also don't allow you to surround another element. This can be a consideration when choosing to use/not use one.
Strongly-Typed Equivalents
However, it's worth noting that what you use the #Html.[Element]For<T>() methods that you gain important features. Note the "For" at the end of the method name.
Example:
#Html.TextBoxFor( o => o.FirstName )
This will handle ID/Name creation based on object hierarchy (which is critical for model binding). It will also add unobtrusive validation attributes. These methods take an Expression as an argument which refers to a property within the model. The metadata of this property is obtained by the MVC framework, and as such it "knows" more about the property than its string-argument counterpart.
It also allows you to deal with UI code in a strongly-typed fashion. Visual Studio will highlight syntax errors, whereas it cannot do so with a string. Views can also be optionally compiled along with the solution, allowing for additional compile-time checks.
Other Considerations
Occasionally a HTML helper method will also perform additional tasks which are useful, such as Html.Checkbox and Html.CheckboxFor which also create a hidden field to go along with the checkbox. Another example are the URL-related methods (such as for a hyperlink) which are route-aware.
<!-- bad -->
my link
<!-- good -->
#Html.ActionLink( "my link", "foo", "bar", new{ id=123 } )
<!-- also fine (perhaps you want to wrap something with the anchor) -->
<span>my link</span>
There is a slight performance benefit to using plain HTML versus code which must be executed whenever the view is rendered, although this should not be the deciding factor.

Depends on what your are doing.
If you have SPA (Single-Page Application) the you can use:
<input id="txtName" type="text" />
Otherwise using Html helpers is recommended, to get your controls bound with your model.

If you want to just display some text in your .cshtml page, I do not recommend #Html.Label and also not to use the html label as well. The element represents a caption in a user interface. and you'll see that in the case of #Html.Label, a for attribute is added, referring to the id of a, possibly non-existent, element. The value of this attribute is the value of the model field, in which non-alphanumerics are replaced by underscores.
You should use #Html.Display or #Html.DisplayFor, possibly wrapped in some plain html elements line span or p.

The helpers are there mainly to help you display labels, form inputs, etc for the strongly typed properties of your model. By using the helpers and Visual Studio Intellisense, you can greatly reduce the number of typos that you could make when generating a web page.
With that said, you can continue to create your elements manually for both properties of your view model or items that you want to display that are not part of your view model.

When it comes to labels, I would say it's up to you what you prefer. Some examples when it can be useful with HTML helper tags are, for instance
When dealing with hyperlinks, since the HTML helper simplifies routing
When you bind to your model, using #Html.LabelFor, #Html.TextBoxFor, etc
When you use the #Html.EditorFor, as you can assign specific behavior och looks in a editor view

#html.label and #html.textbox are use when you want bind it to your model in a easy way...which cannot be achieve by input etc. in one line

Related

Should Angular Elements Be Treated As Blocks or Wrappers

When using element directives I have seen Angular element directives used in two ways:
1. As block level components
The element is styled as display:block, is the component and its children are the component's children, so the element itself is the component.
Use of directive:
<example class="Example"></example>
The directive's html:
<header class="Example-header"></header>
<img class="Example-image">
<footer class="Example-footer"></footer>
2. As an inline wrapper of the component
The element is left as display:inline and effectively acts as an invisible wrapper for the component itself:
Use of directive:
<example></example>
The directive's html:
<div class="Example">
<header class="Example-header"></header>
<img class="Example-image">
<footer class="Example-footer"></footer>
</div>
Obviously each have advantages and disadvantages for example extra markup, loss of layout context due to inline element etc, but is one the correct way? or is this another of Angular's vagaries?
I'm surprised no one responded, but the idea behind creating custom directives is the ability to create reusable pieces of code that fulfill a specific bit of functionality on your site.
This functionality, however, doesn't care about the styles that you are going to use. You can of course conditionally change classes and styles from within Angular, but the core component when dealing with the framework is the data.
With that being said, there is no "correct way" as you bolded in your question. Develop the directive to fit your needs and style of your site.
First this is probably opinion based but i'd really like to share my point of view about this.
If you really follow angular way of doing directives none of theses are a correct way.
Directives are intended to add a behavior to an HTML element.
The less the directive add HTML the best it is as it allow you to have a better control on this element.
Lets take an exemple.
We have a data grid (let say ui-grid, it doesn't really matter)
<ui-grid ...>
...
</ui-grid>
I had a the idea to add some button to add or remove element in the grid.
I first came up with this
<ui-grid ...>
...
</ui-grid>
<button ng-click="addItem()">Add</button>
<button ng-click="removeItem()">Remove</button>
I'm really happy with this and that's ok, but finally i need to use theses buttons in some other views. I'll have to duplicate the HTML, duplicate the JS and adapt it to the collection.
The common mistake
That's obviously not a good idea.
Instead i will do a directive. Lets say "button-list" : it produce the same html and behavior.
<ui-grid ...>
...
</ui-grid>
<button-list></button-list>
That's pretty cool.
Now i have some need. On one view i need the add button to be blue, on an other one i don't need to have a remove button, and on a last one i want the button text to be "X" and "+" (That's was some request by a client in a true story).
I could make a big object with a list of option and etc... but this is really painful and you need to touch the directive each time you need to add a custom different little behavior.
The good way to go
Now lets just think again about what i wanted to do.
I want the button to interact with the grid... and that's pretty much all. This is how we should go building a custom directive.
We could then produce this directive this way :
<div grid-button-container collection="mycollection">
<ui-grid ...>
...
</ui-grid>
<button grid-add-item>Add</button>
<button grid-remove-item>Remove</button>
</div>
So what do we have here ? We have three different directives.
grid-button-container : Its responsibility is to hold the list for the sub-directives.
grid-add-item : It add a function on click that add an element to the collection of grid-button-container.
grid-remove-item : It add a function on click that remove an element to the collection of grid-button-container.
Both grid-add-item and grid-remove-item will be requiring the grid-button-container to be used.
I cannot describe all the implementation of this (it would take too long) but i think this is how directives should be used. Such as almost no angular build-in directives (ng-*) add HTML and just add a behavior i think all the directives should be build in this way.
Pro :
You have a full control about your HTML
Directives are tiny and trivial
This is really re-usable
Cons :
Can be harder and longer to implement.
To make a final point, the two way you're asking about are just different. No one is better than the other it will just depend on your own HTML organisation and it will depend on the directive use.
Hope it helped.

What are the form elements called?

This is silly, but I'm about to explode - inputs, selects, textareas, checkboxes, radio buttons... what is the general name of this type of elements?
I'm creating an AngularJS set of form/input directives that wrap single form field in an object called "input", which consists of "element"-DOM, "scope"-Scope and I want to be able to extract its form element like input, select, etc., but I can't find a proper name for it...
They are called “controls” in HTML 4.01. HTML5 uses the same word, as well as the longer “form control”, but it has some more fine-grained terminology for “form-associated elements”. In practice, controls are often called “form fields”.
The use of “form” in the names is partly misleading, since controls are syntactically permitted outside any forms, too, and such controls can be successfully used when handled with client-side JavaScript.
They are called form controls or form elements or html inputs tags

Is it against input tag semantics to use them for interactivity?

I have been busy making an interactive tab layout using only CSS and I've had someone tell me that this is not the intended semantic meaning of <input> tags. Now, I know that HTML5 focuses a lot more on semantics than previous versions of HTML did, so I was wondering, is something that does something like the following against the input semantics:
<label for="toggleTab" class="togglelabel">Toggle tab</label>
<input type="checkbox" id="toggleTab" class="toggleinput">
<div class="toggletab">Look at this thing hide and show</div>
CSS:
.toggletab, .togglelabel {border:1px solid #AAA;display:block;}
.toggleinput, .toggletab {display:none;}
.toggleinput:checked + .toggletab {display:block;}
(demo)
The standards[1][2] both say the same thing:
The input element represents a typed data field, usually with a form control to allow the user to edit the data.
So to me this seems like this is indeed against what the input tag should be used for (since this has nothing to do with data, but just with displaying certain things to the user or not).
And then of course my followup question would be, if this is indeed not what input tags should be used for according to the standard, is it bad to go against the semantics standards?
Well structurally this will be quite difficult. Inputs need go inside form elements, and if you are going to be using these all over the page, most of your page will be wrapped as one giant form, potentially will nested forms, for search bars, user input and the like.
As your quote says:
The input element represents a typed data field, usually with a form control to allow the user to edit the data.
The control you are suggesting isn't for editing data its for adding graphical user functionality. If you were to bing the input to a form, either by placing the input inline into a form, or using the #form attribute as your comment suggests, what exactly is the semantic of that form? If would have no action, it would have no site to post to, and if an accessibile browser were to try and render the elements of that form in a different way it would have no semantic content.
For the kind of hide/show toggle functionality, I'd recommend instead using an a link and hanging some javascript off that. As stated:
If the a element has an href attribute, then it represents a hyperlink (a hypertext anchor) labeled by its contents.
In this context Hyperlink does not preclude the use of javascript as the acting force on the page, if it did most pages would be non-compliant to the spec. This is backed up by the first type of link suggested in the definition of hyperlink suggests that the link can be "used to augment the current document".
As a side note, in accessible browsers, inputs like these maye be rendered or presented in ways different to what you expect. Each form might be pulled out into a list of possible data editing options, and this would not fit the semantics of what a user might expect.
Semantics & custom behaviour
If the question is about which element has the least implied semantics, I reckon your best bet is the <button type="button"> element: the HTML5 spec describes it as « a button with no additional semantics» which, without scripting, « does nothing » — unlike the <a> element, which has implicit behaviour as a hypertext link and anchor.
The HTML4 forms spec refers to these as 'push buttons', which « …have no default behavior. Each push button may have client-side scripts associated with the element's event attributes ».
Furthermore, the HTML4 spec cites buttons repeatedly in its description of scripts: they are the only element referenced specifically in the introduction to scripts, although inputs also feature in the examples of DOM-event triggered scripts — however, as buttons are non-self-closing, they can contain other DOM nodes, which may make them more flexible depending on your needs.
Non-<input> solution
Using the push button, custom behaviour can be inferred by using data-* attributes for CSS selectors:
.toggleinput[ data-checked ] + .toggletab {
display:block;
}
…and scripted as follows:
// Use Array's forEach to loop through selection
Array.prototype.forEach.call(
// …of all `.toggleinput` elements
document.querySelectorAll( '.toggleinput' ),
function bind( input ){
input.addEventListener( 'click', function toggleCheckedState(){
// `dataset` is an object representation of data-* attributes
if( this.dataset.checked ){
// Remove the attribute if it exists
delete this.dataset.checked;
}
else {
// Declare it if it doesn't
this.dataset.checked = true;
}
}, false );
}
);
Forked code demo

Is there a generic attribute for all HTML elements aside from ID and class?

Like a tag that I can use to store some necessary info? But really isn’t required or used by the HTML? Works like the tag attribute for objects on Visual Basic?
Up until HTML5 no. With HTML 5 there is provision for this with the data-* attribute.
For example:-
<div id="myStuff" data-mydata="here is my data">
In current technology there is no "official" away to do this. However all browsers allow you to add any arbitary attribute to a HTML element so in HTML4 you can do this:-
<div id="myStuff" data-mydata="here is my data">
Which as you can see is identical but not offically sactioned and if you want strict XHMTL compliance will be considered "broken".
You can access the attribute just as you would any other:-
var mydata = document.getElementById("myStuff").getAttribute("data-mydata");
You could perhaps use the html5 data-* attributes? It'll fail validation on html4, but it is still probably the best option...
If you're storing data to use in javascript, you can also use something like jQuery's Metadata plugin. Basically, you can store data within the element's class="" attribute, like so:
<div id="aaa" class="class1 class2 class3 { type: 'food', color: 'green' }"></div>
Then in javascript:
alert($('#aaa').metadata().color) // "green"
Other kits use the title or rel attributes to store data. While this is more validation friendly, it may or may not be better than using AnthonyWJones' answer of just using non-standard attributes. It'll "break" validation, but then again according to Dojo, custom attributes are perfectly valid HTML, even if they don't validate against a DTD.
So no - there isn't a single well accepted specific attribute where you can dump all data. All existing attributes are for specific uses. But you can either 1) create your own attributes, or 2) coopt an existing tag to reuse for your purposes. Just wanted to point out the alternative.
Have a look at www.htmlref.com or W3C for the used attributes.
Other than those you can just add your own, they will render and they will be accessible via code for instance in C# you can access a controls attribute collection.
Control.Attributes["MyCustomAttribute"] = "Hello World";
there’s rel and rev attributes, which work in elements with an href-attribute. they have a semantic meaning, but are often abused as an attribute to store additional information

Is there a legitimate use-case for putting a fieldset outside of a form?

I was recently corrected, and according to the HTML4 DTD, it is legitimate to use a fieldset outside of a form:
http://www.w3.org/TR/html401/sgml/dtd.html#block
Previously I had not known this, and wonder if anyone can think of a legitimate use case for doing so. I feel like using one to decorate would be frowned upon by most designers. So is there a legitimate use case, or can you link to a site where this has been found appropriate and used as such?
I used a field set to decorate sections when printing documents. For example an invoice might have a Bill To and a Ship To, and drawing the frame around them with the legend text embeded in the frame can look really slick.
I think its more than legit to use it for decoration. Its simple and elegant and with the use of tag its pretty nice.
Check w3schools example out
I don't think there is a legitimate case to semantically have a fieldset outside a form element, since a fieldset is a set of (input) fields - the clue's in the name! If you have input fields, you will likely always have a form, even if you're not posting back to the server.
I have occasionally used from a presentational aspect, because the fieldset+legend combo is impossible to replicate exactly in CSS, specifically, the broken line behind the legend.
It is acceptable to use all form field control outside of a form element, including fieldset.
This is appropriate wherever you have fields that only talk to JavaScript, instead of ever being submitted back as to the server side.
(This didn't originally used to work in Netscape 4, but that's hardly a concern this century...)
Well, using it to decorate can be frowned upon by designers AND be legitimate, so there is a legitimate use case.
A form is simply a container for the fields you wish to submit via post back. Most regular site pages may not even have one. That said, using a fieldset as a styling tag is legitimate and has nothing at all to do with whether a form tag exists or not.
You can use a fieldset to wrap multiple form controls that you need to disable together:
<fieldset disabled>
<input type="text" placeholder="disableable input" />
<button type="button">Some action that needs to be disabled</button>
<button type="button">Some other action</button>
</fieldset>