which HTML helper bypasses all templates and renders a simple string? - asp.net-mvc

this question I got from some tests:
Which of the following templated HTML helpers of MVC bypasses all
templates and renders a simple string representation of the specified
model property?
and options:
Display
Label
DisplayText
Editor
as I understand, it means, that which helper displays property as string? The correct answer is Label?

the correct answer is DisplayText and don't get confused with DisplayTextFor which is a strongly typed version of DisplayText and returns the annotation value of your model attribute (if predefined) or null otherwise

Related

Using HTML.EditorFor Vs using HTML.CheckBox

I have the following model class which contains a bool value:-
Public class Server
{
public bool IsIPUnique { get; set; }
}
Currently i am using the following to display the check box inside my Razor view:-
<input type="CheckBox" name="IsIPUnique" value="true" #(Html.Raw(Model.IsIPUnique ? "checked=\"checked\"" : ""))/> IP Unique.
but i read about the EditorFor template, and it can automatically create the check box and check/uncheck it based on the model values so i tried the following :-
#Html.EditorFor(model=>model.IsIPUnique)<span>test</span>
so my question is if i can replace my old code with the new one that uses the EditorFor ?, or asp.net mvc might deal with these values differently ?
Thanks
Basically you have 3 possibilities:
Write HTML manually (as you have done)
I would avoid writing the HTML manually if there is a HTML helper available.
Manually written HTML is prone to errors which can cause problems with model binding.
Use the specific HTML helpers (Html.CheckBoxFor)
The specific HTML helpers add a layer of abstraction to all controls.
It's easy to modify the template of all controls that use the same HTML helper and it makes your views more readable.
Use the general EditorFor
The EditorFor HTML helper is great if your model datatypes change often.
The EditorFor will adjust the input fields automatically to the new datatype and won't throw an error (as with the specific HTML helpers).
It is also a bit harder to add HTML attributes to the EditorFor while the specific HTML helpers often have overloads for them.
However, this is fixed in MVC 5.1: http://weblogs.asp.net/jongalloway/looking-at-asp-net-mvc-5-1-and-web-api-2-1-part-3-bootstrap-and-javascript-enhancements
Conclusion: in your case I would use the CheckBoxFor HTML helper because the datatype won't change likely and it will make the view cleaner

Is this by design in MVC Model Binding?

A simple scenario that I've never seen before, but a colleague has just hit - MVC3
Create an action method MyAction(int myProperty = 0)
Create a model that has a property MyProperty
Pass an instance of this model to a strongly typed view, but set the property to 10 in code (don't use the query string parameter!)
In the view, Html.TextBoxFor(x => x.MyProperty)
This should render 10 in the text box.
Now call the action method MyAction?myProperty=8
Shouldn't this still render 10 in the text box?
I see that I can override the property discovered by the expression and assume this is because they are the same name (Query String parameter and model property). Eveything is then in the ViewData but one overrides the other.
Is this by design?
This is by design - ModelState is the highest priority value-provider for model properties, higher than even model itself. Without query string parameter, ModelState does not contain value for MyProperty, so framework uses model value.
You can use ModelState.Remove("MyProperty") to ensure using model value
If you look at the source code for Html.TextBoxFor you will see that if a value exists in ModelState then it will always use that value before any other.
string attemptedValue = (string)htmlHelper.GetModelStateValue(fullName, typeof(string));
tagBuilder.MergeAttribute("value", attemptedValue ?? ((useViewData) ? htmlHelper.EvalString(fullName, format) : valueParameter), isExplicitValue);
If the value is in ModelState, then it doesn't matter what you set in code.

ASP.NET MVC Editor Templates

I have a question about Editor Templates. For example I have a model with date field, product prize field and weight of product field. I have successfully created Editor Templates for DateTime and Decimal. I'm given to understand that when I use EditorFor for any field it takes template depending on a data type of the field.
So when I use: EditorFor(m=>m.DateOfBirth) which is DateTime format it looks for DateTime template in EditorTemplates folder and EditorFor(m=>m.ProductPrice) which is double it looks for Double template, etc.)
Question is how can I differ that I want to use one Decimal template with string format ##0.00 for (double)ProductPrize and another template with format ##0.0000 for (double)ProductWeight?
Any help would be appreciated
You may want to use an overload of EditorFor, which accepts template name as second parameter, like:
EditorFor(m=>m.ProductPrice, "PriceEditorTemplate")
More info: MSDN
Define it in your model using the UIHint attribute:
[UIHint("MySpecificEditorTemplate")]
public ProductPrice {get;set;}
And EditorFor will use the MySpecificEditorTemplate.cshtml for example.

MVC ViewBag seems to automatically populate TextBox in my View

In my controller I have the following:
ViewBag.VendorName = vendorname;
In my View I have the following:
#Html.TextBox("VendorName")
It appears that the TextBox VendorName is being populated with the content of ViewBag.VendorName.
This is what I want but didn't know that from a ViewBag you can directly populate a TextBox.
Is this expected and why does this happen?
According to Steve Sanderson in Pro MVC:
HTML helper methods populate their value from the following places (in this order):
ViewData.ModelState["VendorName"].Value.RawValue
For string based helpers, the value parameter passed to the helper method, or if you didn't supply one, then ViewData.Eval["VendorName"] (and ViewBag.VendorName as you're seeing here)
For strongly typed helpers, the corresponding property value on your Model object

ASP.Net MVC, Dynamic Property and EditorFor/LabelFor

I am using MVC 3 w/ Razor and using the new dynamic ViewBag property. I would like to use the ViewBag property with the EditorFor/LabelFor Html helpers but can't figure out the syntax.
The View does have a #model set, but the object I am trying to use is not part of that model. I am aware I can create a ViewModel but that is not what I am after.
Can anyone help?
Controller:
var myModel= _repo.GetModel(id);
var newComment = new Comment();
ViewBag.NewComment = newComment;
return View(myModel);
View:
#model Models.MyModel
#(Html.EditorFor(ViewBag.NewComment.Comment))
I haven't tried it, but this should work I think.
#(EditorFor(m => ViewBag.NewComment)
It is possible to use a Linq-to-SQL syntax, but use a completely different object on the right side.
Not knowing what your Comment Model looks like, my gut reaction would be to just do:
#Html.EditorFor(ViewBag.NewComment)
However, because ViewBag is dynamic, you may need to cast NewComment before you use it, in order to get the EditorFor magic.
#Html.EditorFor(ViewBag.NewComment as Comment)
Update
Strike that, EditorFor can only accept an Expression as a parameter, and that Expression must return a property of the page model. I don't think EditorFor or EditorForModel are going to be of any use to you if you don't want to use a ViewModel. Have you considered switching the roles of whatever it is you're using the Model for, with that of the ViewBag?
If for some reason I need to use ViewData to pass the model into my view I do the following to allow for the Html.DisplayFor() helpers.
In the views code block I cast the ViewData model object to its underlying type
var newCommentModel = ( NewComment )ViewBag.NewComment;
Then I assign the following expression to the helper using the strong-typed reference
#Html.DisplayFor( model => newCommentModel )
The expression tree now contains a strongly-typed model and the DisplayTemplate is correctly displayed.

Resources