Please can anyone tell what does "{Binding .}" mean? The point refers to what? I know that we have refer to a property but I don't understand when I have to put this point
{Binding} in XAML is a markup extension, specifically, it's BindingExtension
If you look at this class, you'll see that it has a Path property. In XAML you use it like this:
{Binding Path=PathThePublicPropertyOfTheBindingContext} or, shorter by omitting Path=:
{Binding PathThePublicPropertyOfTheBindingContext}
If the object you want to bind to does not have a property you bind to, but you rather want to bind to the object itself, you use .. Say, your binding context is a string type:
public string MyObject = "Hello World";
BindingContext = MyObject;
and in XAML
<Label Text="{Binding .}">
it would display "Hello World", the content of the object itself.
Related
I'm trying to change the emitted name of the html input created by #Html.HiddenFor.
The code I'm using this:
#Html.HiddenFor(e => e.SomeProperty, new { #id = "some_property", #name = "some_property" }
Now this works for the id, however it doesn't work for the name. Now I don't really care for the id now, I need the name to change, because that's the one that get's posted back to the target server.
Is there
A property I can apply on SomeProperty in my model?
A way in the Html.HiddenFor to override the name property?
Or am I stuck to do a plain <input ...> by hand?
You need to use the Html.Hidden (or write out the <input ...> by hand) instead of the Html.HiddenFor
#Html.Hidden("some_property", Model.SomeProperty, new { #id = "some_property" })
The goal of the strongly typed helpers (e.g the one which the name end "For" like HiddenFor) is to guess the input name for you from the provided expression. So if you want to have a "custom" input name you can always use the regular helpers like Html.Hidden where you can explicitly set the name.
The answer from unjuken is wrong because it generates invalid HTML.
Using that solution generates TWO name attributes:
<input Name="some_property" name="SomeProperty" id="some_property" type="hidden" value="test" />
So you will have Name="some_property" AND name="SomeProperty" which is INVALID HTML because an input can only have ONE name attribute! (although most browers happen to take the first Name="some_property" and don't care about the second one...)
If you use:
#Html.HiddenFor(e => e.SomeProperty, new { #id = "some_property",
#Name = "some_property" });
Notice the capital "N" in #Name. It´ll work.
I was curious as to why specifically overriding the name attribute wouldn't work. Unless I capitalized it (i.e. new {#Name = 'somename'} ), then it doesn't seem to work. As others have pointed out, this only works because it generates duplicated name attributes and Chrome cleans it up.
I looked at the latest MVC source code to figure out what is going on. Consider the following snippet from the GenerateInput method in DefaultHtmlGenerator.cs:
var fullName = NameAndIdProvider.GetFullHtmlFieldName(viewContext, expression);
if (string.IsNullOrEmpty(fullName))
{
throw new ArgumentException(
...
}
var inputTypeString = GetInputTypeString(inputType);
var tagBuilder = new TagBuilder("input");
tagBuilder.TagRenderMode = TagRenderMode.SelfClosing;
tagBuilder.MergeAttributes(htmlAttributes);
tagBuilder.MergeAttribute("type", inputTypeString);
tagBuilder.MergeAttribute("name", fullName, replaceExisting: true);
We can see here, the problem is that, regardless of whatever name property you provide, it will be overridden by the last call to MergeAttribute, which will use whatever logic it is that assigns to the variable fullName from the GetFullHtmlFieldName method.
I sort of understand why they enforce this behavior, guessing it has something to do with controlling the names used in the postback to guarantee it works with the model binder.
In any case, to make this happen, I say just manually construct the input element and don't use the razor view helper.
never worked for me (aspnet.core)
I used plain
<input type="hidden" id="#myid" name="#myname" value="#Model.prop" />
and worked like a charm. No need for HtmlHelper HiddenForModel.
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.
Not that it really matters but I want to follow the best practices. When creating View Models is it considered best practice to use property getters or methods? e.g
public class ProductViewModel
{
private readonly Product _product;
public ProductViewModel(Product p)
{
_product = p;
}
public string Price
{
get { return string.Format("${0}" _product.Price.ToString("N2") };
}
}
Considering that this is a simple example is it better to use a method?
public string GetPrice()
{
return string.Format("${0}" _product.Price.ToString("N2");
}
What are the pros / cons between the two?
If you're using MVVM, then you're using databinding. Databinding binds to properties, not methods. (See the docs for the Binding.Path property -- there's not a single occurrence of the word "method" on that page. It's all about properties.)
So there's no contest. Use properties, because that's what the binding system supports.
I would lean towards a property and away from a function. The point of a view model is to present the model in a fashion suitable for displaying in a view. Usually the view and the view model talk to one another through binding, often done in XAML.
By using a method instead of a property you make wiring up the view and the view model less turn key.
Say you end up needing that price elsewhere, keeping it formatted in the old code but without the formatting in the new code. With a method you'd now need another method, or a property to get the price. With the property, you could just apply a StringFormat to the first binding.
<!-- Old code -->
<TextBlock Text="{Binding Price}" />
<!-- New code -->
<TextBlock Text="{Binding Price, StringFormat=${0:N2}}" />
<awesome:MoneyUpDown Value="{Binding Price}" />
If you are using MVVM, chances are you want INotifyPropertyChanged support, in which case properties are the way to go. There are a number of frameworks (e.g. Caliburn.Micro) that help you minimize repetitive crud code, like wiring up the notifications.
The original question was about the MVVM pattern. With plain MVC (without data binding), the answer is not as clear cut. Personally, I would still use a property over a method when getting simple data when no extra calculation or data access is required.
one caveat with the first method is that you would have to implement a second property to be able to get the price without formatting
I am using the implementation give at Bind TextBox on Enter-key press to handle the enter key for text box.
But I am using MVVm pattern for my application. Therefore I have defined the ICommand handler in my VieModel class. I want to bind it to view.
The sample application uses
InputBindingsManager.UpdatePropertySourceWhenEnterPressed="TextBox.Text"
and I want to use
InputBindingsManager.UpdatePropertySourceWhenEnterPressed="{Binding myCommandHandler}"
instead.
Can anybody suggest what modification are required in the code?
You can go for inputbindings for a textbox. in this you can bind a Icommand object to command property ok keybindings
Here is the sample code
<TextBox Text="{Binding Firstname, UpdateSourceTrigger=PropertyChanged}">
<TextBox.InputBindings>
<KeyBinding Key="Enter" Command="{Binding ValidationCommand}">
</KeyBinding>
</TextBox.InputBindings>
</TextBox>
I've got a View where I use a naming-convention on my text-fields, to indicate what should be done with the content once it is posted back to my controller.
The format is similar to:
<input type="text" name="RegistrationLine#ID" />
for updates
<input type="text" name="CreateRegistrationLine#LineNumber" /> for create
Now since I'm using this Naming-convention, regular model-binding isn't possible. But I've been reading up a bit on the subject and did find a bit of an indication that it would be possible to write a custom model binder, that should be able to help parse and bind these form elements and instantiate the objects correctly.
Please read: Bind formValue to property of different name, ASP.NET MVC
This is a bit similar to what I am doing except, I have the additional complexity of having appended information in the formelement-name that I am trying to bind to.
Am I way off base here? and if not, can any of you drop a few lines of code to show how you would start this model-binder off..
If this is a very bad approach to what I am really trying to achieve, I would love to hear suggestions for better approaches. Just note that what I want to be able to do is post back both updates and creates in one go.
I kinda have to agree with #jfar and #omar. I don't think a custom model binder is where you want to be in this instance.
You can pass a complex type to your view and simply use the full stop like #jfar mentioned.
id="Model.Person.Name.FirstName" will happily bind to an object named Person that has a class in it called Name that has a property called FirstName.
Now if you want to do some special checks on the data you could implement a partial class which would do the validations etc and populate the ModelState errors.
public partial class Name
{
public void Validate(){ }
public int CreateRegistrationLine(){ }
public bool DoSpecialActions(){ }
}
It's a little unclear what your special actions are doing so my example above may not be what you want.