Should I use Html.Label helper? - asp.net-mvc

In an MVC project I use an HTML.Label helper as follows:-
#Html.Label("FirstName", "First Name", New With {.class = "FieldLabel"})
Which outputs
<label class="FieldLabel" for="FirstName">First Name</label>
I've also got a corresponding input for this label.
This might sound like a stupid question, but if I was just to enter the direct output into my view instead of using the HTML helper is there absolutely any difference? So are there any advantages/disadvantages to using an HTML helper for a label?

There is no difference.
For simple stuff like labels, I don't really see the benefit of using html helpers. The helper code is longer than the actual html.
However, html helpers are great for model binding.
So if i want to bind a label or other form elements to my ViewModel i use
#Html.LabelFor(m => m.FirstName)
#Html.TextboxFor(m => m.FirstName)
This ensures that model binding works correctly. The form elements are outputted with the necessary attributes so that when the form is posted to the server, the model parameter is populated automatically on the server side.
It also takes sure of making sure that your labels are linked to the correct form elements.
The #Html.LabelFor helper will output the following html
<label for="Username">Username</label>

HtmlHelpers are designed to generate dynamic content; So, if you have such a scenario for your project those are necessary.
In your code
#Html.Label("FirstName", "First Name", New With {.class = "FieldLabel"})
everything is static, so there is no obligation to use HTMlHelper.

Html.Label gives you a label for an input whose name matches the specified input text

Related

difference in input type=Checkbox, #HTML.CheckBox and #HTML.CheckBoxFor?

I m new to MVC and confused what is difference in <Input type="Checkbox">, #HTML.CheckBox and #HTML.CheckBoxFor.
Can you please guide why two helpers are provided for same thing ? In which situation which one should be used ?
Thanks
Edit:
Added Input type=checkbox
<Input type="Checkbox"> is Html markup for a checkbox and #Html.CheckBox & #HTML.CheckBoxFor are Html Helpers for Razor view engine..
suppose your viewmodel has a property Person.HadDinner, then usually for model binding to work properly you will have to name the checkbox Person.HadDinner and id as Person_HadDinner..
you can use #Html.CheckBox like
#HTML.CheckBox("Person.HadDinner", Model.Person.HadDinner)
but if you are using #HTML.CheckBoxFor, it will be strongly typed..
#HTML.CheckBoxFor(x => x.Person.HadDinner)
in both the cases, final output markup will be
<input type="checkbox" id="Person_HadDinner" name="Person.HadDinner">
The CheckboxFor (MSDN)
Returns a check box input element for each property in the object that
is represented by an expression.
This means a checkbox element is created for each property in the expression provided. Where as Checkbox (MSDN)
Returns a check box input element by using the specified HTML helper
and the name of the form field.
This creates a simple Checkbox element with the (optional) attributes provided.
Typically when referencing a property of an object (or the View Model) the most desired technique is to use CheckboxFor as the checkbox will be formatted correctly against your model.
Hope this helps.
EDIT: Response to OP Changes.
Both the CheckboxFor and Checkbox generate standard HTML output such as below.
#Html.CheckboxFor(m => m.SomeProperty)
<input type="checkbox" name="SomeProperty" id="SomeProperty" />
#Html.Checkbox("SomeProperty")
<input type="checkbox" name="SomeProperty" id="SomeProperty" />
The helper methods simply generate the HTML required to meet the expressions and attributes defined in the helpers.
Additionally, you dont have to use the helpers. You can write your HTML elements directly as needed.

Direct Model.Property versus Html Helper DisplayFor in Razor

Is there a reason to use preferably one of these:
#Model.Property
#Html.DisplayFor(m => m.Property)
I never arrived in a crossroad where one works differently from the other.
There is any difference?
Model.Property - as you know - will just write out the value of the property in question. Html.DisplayFor(m => m.Property), on the other hand, will call a display template, which can render out other markup around the property value.
For example, you might define a display template like so:
#model String
<div class="property-wrapper">
<p>#Model.Property</p>
</div>
The surrounding divs will be rendered around the value of the property when using DisplayFor (if the display template is selected, which typically means it has a filename matching the property's type, is specified in the UIHint attribute for the property, or is explicitly specified in the call to DisplayFor.
You also have access to model metadata in your display templates, meaning you can do something like this:
<div class="property-label">
#Html.DisplayNameForModel()
</div>
<div class="property-value">
#Model.Property
</div>
Display templates give you a huge amount of flexibility and reusability. The best way to explore this is to start building custom templates and see where it takes you.

MVC4 Razor - #Html.DisplayFor not binding to model

I am trying to find me feet with MVC4 Razor and I'm stuck with this simple problem.
When I use #Html.DisplayFor the model is always sent back as NULL, but when I use #Html.TextBoxFor this model is fully populated, what am I missing?
Thanks in advance
This is a common issue that many people miss in the asp.net mvc framework. Not just the difference in the helpers such as HiddenFor, DisplayFor, TextBoxFor - but how exactly the framework sets up automatically collecting and validating these inputs. The magic is all done with HTML5's data-* attributes. You will notice when looking at the input tag generated that there are going to be some extra properties in the form of data-val, data-val-required, and perhaps some additional data properties for types, for example numerics would be data-val-number.
These data attributes allow the jQuery extension jquery.validate.unobtrusive.js to parse the DOM and then decide which fields to validate or generate error messages.
The actual collection of posted data is reflected from the name property. This is what should map up to the model that is in the c# or vb [HttpPost] method.
Use HiddenFor when you want to provide posted data that the user does not need to be aware of.
Use DisplayFor when you want to show records but not allow them to be editted.
Use TextBoxFor when you want to allow user input or allow the user to edit a field.
EDIT
"the purpose of this view is to enable the user to view the data before submitting it to the database. Any ideas how I can achieve this?"
You could accomplish this with a duo of HiddenFor and DisplayFor. Use HiddenFor to have the values ready to be posted, and DisplayFor to show those values.
DisplayFor will not do the Model binding. TextBoxFor will do because it creates a input element in the form and the form can handle it when it is being posted. If you want to get some data in the HttpPost action and you dont want to use the TextBoxFor, you can keep that pirticulare model proeprty in a hidden variable inside the form using the HiddenFor HTML helper method like this.
#using(Html.BeginForm())
{
<p>The Type Name is</p> #Html.DisplayFor(x=>x.TypeName)
#Html.HiddenFor(x=>x.TypeName)
<input type="submit" value="Save" />
}
Use both DisplayFor and HiddenFor. DisplayFor simply displays the text and is not an input field, thus, it is not posted back. HiddenFor actually creates <input type="hidden" value="xxxx"/>
DisplayFor builds out a HTML label, not an input. Labels are not POSTed to the server, but inputs are.
I know this is a bit of an old question but you can roll your own, custom combined display control as shown below. This renders the model value followed by a hidden field for that value
#Html.DisplayExFor(model => Model.ItemCode)
Simply use what the framework already has in place
public static MvcHtmlString DisplayExFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> ex)
{
var sb = new StringBuilder();
sb.Append(htmlHelper.DisplayFor(ex));
sb.Append(htmlHelper.HiddenFor(ex));
return MvcHtmlString.Create(sb.ToString());
}
Do you mean during a form post? If you use DisplayFor, this creates a element which does not contain any form values. Typically you use these in conjunction with each other to create a label for your textbox, then using the Html.TextBoxFor to allow users to modify the data element.
Example:
#Html.DisplayFor(x=>x.Item)
#Html.TextBoxFor(x=>x.Item)
Will Render
Item <a text input field following>
Or in HTML
<label for="Item">Item</label><input type="Text" id="Item" name="Item"/>

MVC #Html.Display()

I have something like:
<input type="text" name="TerrMng" id="TerrMng"/>
in HTML. What is the equivalent of the above using #Html.Display?
I tried using: #Html.Display("TerrMng", TerrMng)
but was not successful. Note that I like to use #Html.Display but not sure how to translate the ID value so that it shows up.
The Display method is not for creating input boxes. You'd want to use:
#Html.TextBoxFor(m => m.TerrMng);
or the templated helper method:
#Html.EditorFor(m => m.TerrMng);
I'm assuming that you want to use modelbinding. If not, if you really just want to use a helper to simply make an input tag, use:
#Html.TextBox("TerrMng");
This would be sent to the client:
<input id="TerrMng" type="text" value="" name="TerrMng">
The first 2 methods above would result in the exact same html, if model.TerrMng was "" or String.Empty. If for some reason you don't want the value attribute, you'll need to type it out yourself.
This should do the trick if you are just wanting to display the data and not allow the user to edit the information.
#Html.DisplayFor(m => m.TerrMng);
Edit:
what-is-the-html-displayfor-syntax-for is another question on stackoverflow that may give you some more guidance.
Edit:
TerrMng does not exist on PageLoad so you cannot use the Html.Display in that way. You need to create it and fill its value with the value received from the jQuery. In this case where you would have to do the following:
HTML
#Html.Display("TerrMng"); // This creates the label with an id of TerrMng
jQuery
$("#TerrMng").val(TerrMng); // This puts the value of the javascript variable into the label
You could try something based on this. This is not exact but you could get some idea.
#Html.TextBoxFor(yourmodel => model.yourModelFieldname, null)
#Html.Display() is used instead of #Html.DisplayFor() when your model is not known at compile time, or if you prefer to work with strings, rather than with strong types. For example, these 2 are equivalents (given that your model is some class):
#Html.DisplayFor(m => m.MyProperty)
and
#Html.Display("MyProperty")
But the additional cool feature of the Display() method is that it can also do the lookup in the ViewData, and not just in your Model class. For example, here is a way to display the HTML for the property on a random object, given that we know it has a property named "Blah" (the type of the object doesn't really matter):
#{ ViewData["itsawonderfullife"] = SomeObject; }
<div>#Html.Display("itsawonderfullife.Blah")</div>
This way, we are telling HtmlHelper to look into the ViewData, instead of our Model, and to display the property Blah of a given SomeObject.

Differences between Html.TextboxFor and Html.EditorFor in MVC and Razor

Why by default were these changed when adding a new "edit" view? What are advantages when using EditorFor() vs. TextboxFor()?
I found this
By default, the Create and Edit scaffolds now use the Html.EditorFor helper instead of the Html.TextBoxFor helper. This improves support for metadata on the model in the form of
data annotation attributes when the Add View dialog box generates a view.
Quoted from here.
The advantages of EditorFor is that your code is not tied to an <input type="text". So if you decide to change something to the aspect of how your textboxes are rendered like wrapping them in a div you could simply write a custom editor template (~/Views/Shared/EditorTemplates/string.cshtml) and all your textboxes in your application will automatically benefit from this change whereas if you have hardcoded Html.TextBoxFor you will have to modify it everywhere. You could also use Data Annotations to control the way this is rendered.
TextBoxFor: It will render like text input html element corresponding to specified expression. In simple word it will always render like an input textbox irrespective datatype of the property which is getting bind with the control.
EditorFor: This control is bit smart. It renders HTML markup based on the datatype of the property. E.g. suppose there is a boolean property in model. To render this property in the view as a checkbox either we can use CheckBoxFor or EditorFor. Both will be generate the same markup.
What is the advantage of using EditorFor?
As we know, depending on the datatype of the property it generates the html markup. So suppose tomorrow if we change the datatype of property in the model, no need to change anything in the view. EditorFor control will change the html markup automatically.
The Html.TextboxFor always creates a textbox (<input type="text" ...).
While the EditorFor looks at the type and meta information, and can render another control or a template you supply.
For example for DateTime properties you can create a template that uses the jQuery DatePicker.
This is one of the basic differences not mentioned in previous comments:
Readonly property will work with textbox for and it will not work with EditorFor.
#Html.TextBoxFor(model => model.DateSoldOn, new { #readonly = "readonly" })
Above code works, where as with following you can't make control to readonly.
#Html.EditorFor(model => model.DateSoldOn, new { #readonly = "readonly" })
There is also a slight difference in the html output for a string data type.
Html.EditorFor:
<input id="Contact_FirstName" class="text-box single-line" type="text" value="Greg" name="Contact.FirstName">
Html.TextBoxFor:
<input id="Contact_FirstName" type="text" value="Greg" name="Contact.FirstName">

Resources