How does MVC decide which value to bind when there are multiple inputs with the same name? - html

I have an edit page where several fields are conditionally disabled, based on the user's role. When the fields are disabled, their values are not posted to the server (as expected), which causes the ModelState to be invalid, as the values are required.
To get around this, I want to add Html.HiddenFor() for the fields; so that a value will still get posted (and so that it will retain those values if the View is returned). However, in the case that those fields are not disabled, I will then have both a TextBoxFor and a HiddenFor going to the same model property.
I have run a couple tests, and it appears that when this happens, the value of the first element on the form will be binded to the model, while the next one just gets ignored. If this is the case, then I should be able to just put the HiddenFor after the TextBoxFor, in which case the value of the hidden input will only be posted when the regular input is disabled.
#Html.TextBoxFor(m => m.FirstName)
#Html.HiddenFor(m => m.FirstName) #*Only gets binded to the model if the above text box is disabled*#
(There is some JavaScript that conditionally disabled the visible TextBox).
So two questions: 1) Is it documented that MVC binding will always work this way; can I safely have both of these fields?
And, 2) Is there a better approach to accomplishing this? I know that I can but the HiddenFor inside an #If statement so that it will only get created if the TextBox is disabled; but that is a lot of extra logic in the View that I'd like to avoid.

The DefaultModelBinder reads the values from the request in order and binds the first matching name/value pair and ignores subsequent matches (unless the property is IEnumerable). This is how the CheckBoxFor() method ensures a true or false value is always submitted to the controller (the method generates a checkbox with value="True" and a hidden input with value="False"), so you can safely add the hidden input after the textbox.
One option you might consider rather than a disabled textbox, is to make it readonly, which means it will always submit a value, therefore you only need one input (and you can always style it to look disabled if that is what you want).

Related

What is the correct and most safe way to check if HTML form checkboxes and such have been POST-set?

This has confused me since the early days. Maybe it's just in my head, but it seems to me as if this has varied over time, between browsers, and possibly even depending on the local language/locale.
Basically, whenever I need to check if a HTML input of type "radio" or "checkbox" has been set, I always do:
if (isset($_POST['the_name']) && trim($_POST['the_name']))
// do stuff
This just makes sure that the POST variable is sent whatsoever (which in itself doesn't mean that it was actually checked/selected, as far as I can tell, since its "value" can be an empty string) and that it's something other than '' (empty string). It seems like this has worked for a long time, but I have two problems with it:
It's ugly. I need to abstract it into a function, but then I want to know if it's a good idea in the first place, or wrong somehow.
It makes the assumption that any non-empty string value means "checked" or "selected", whereas the standard may say a specific string value such as "on", or maybe any number of such strings depending on the language/locale.
Are there cases where my above code falls apart? Do browsers ever submit POST forms where they include names which have no user input/selection in the HTTP request? Or does the existence of a name in the POST blob mean that that "field" has been actively changed/set/checked/selected?
The idea behind checkboxes is that the value is sent over to the server only if the checkbox was checked when submitting the form. The value can be anything, even an empty string. As long as the field is part of the transmitted form it means the box was ticked.
The value attribute is one which all <input>s share; however, it serves a special purpose for inputs of type checkbox: when a form is submitted, only checkboxes which are currently checked are submitted to the server, and the reported value is the value of the value attribute. If the value is not otherwise specified, it is the string on by default.
This means you could have a form like this:
<form action="" method="get">
<input type="checkbox" name="c1" value="">
<input type="submit" value="Send">
</form>
If the checkbox is not checked when submitting then $_GET will be an empty array.
If the checkbox is checked then the value of $_GET will be:
array('c1' => '');
To check whether the box was ticked when sending the form you only need isset()
if (isset($_POST['c1']) {
// The box was checked!
}
Sometimes you would like to assign a value attribute to your checkbox. In such situations you can use the shorthand operator for isset() function ??.
// Create a variable from the checkbox value or assign an empty string if the box was not checked
$nyCheckbox = $_POST['c1'] ?? '';

How to prevent AngularJS from validating form controls for the first time

I my form I have some input controls which are bounded with controller's scope data. Based on users selection I am bounding selected item by using ng-model to input controls.
I am validating those inputs by using ng-maxlength ,minlength ,ng-pattern and other inbuilt validation directives.
Class for highlighting the invalid values.
.ng-invalid { border-color:red; }
But when user wants to add a new product, then I am creating an empty object and adding it to controller's scope data.
At the very first time while creating new item I don't want to highlight every thing with red, because very thing is empty.
Is there any way by which I can highlight invalid input on their focus and after it will show as invalid until use put some valid values in it.
When use select any existing data then I am validating control at that movement.
You can use forms' $pristine as a condition for your classes.

HTML single Checkbox: Best practise whether to use value attribute or not

today i had a discussion with my colleague. The question was whether to use the additonal value attribute for a single HTML checkbox or not.
My preffered way is using a single checkbox without a additional value attribute and in backend doing a check like if
if (request.getParameter(checkboxName) != null)) {
...
}
My colleague argues that is would be more transparent using a single checkbox with a additonal checkbox value attribute like value="true" and doing a backend check like
if (Boolean.valueOf(request.getParameter(checkboxName))) {
...
}
As we want to make a small convention about our internal checkbox handling im now trying to find a "best practise" but couldn't find yet. I saw so far only examples with multiple checkbox with the same name. In this case of course it makes sense for me to use different values.
For me it seems to be a bit overhead using a value attribute in case of a single checkbox since i get always a String with "on" if its activated/checked.
We are using a Java Servlet/JSP MVC environment and im not 100% sure if this "on" comes from ServletRequest.getParameter.
I see reasons for following either method, which means there's probably no noticable difference between them. Whichever you pick will work out fine; just make sure you pick one. You could flip a coin or do a thumbwar or something.
As long as a single approach is consistently used, both will work. Yours is less code and doesn't require boolean conversion, the otherĀ“s html is more consistent with multiple checkboxes but will also break if you put the wrong value for whatever reason.
You could always do a bit of both and insert values in html for clarity but check for != null in the code and get the best of both options.
It makes no difference server-side as long as you are not checking the parameter for having a specific value. By HTML5 definition, which just establishes the longstanding practice as the rule, a checkbox element has the value on by default. This means that your server-side code cannot distinguish between data coming from <input type=checkbox name=foo> and data coming from <input type=checkbox name=foo value=on>.

Can't remove the value entered in the djFilteringSelect dojo control in xPages

I am using the djFilteringSelect control to show values in a dropdown as user type a value.
The lookup and typehead is working fine. The user type a letter and the dropdown allow the user to select a value which is then displayed in the dropdown field.
If the user now decide to remove the value first selected so that the combobox is empty and leave the field, then the first value in the list is now automatically filled in.
The consequence of this is that if the user have added a value there is no way to remove the value and leave the box emtpy.
I am using required=false for both the control and the dojo attribute but it does not seem to help. There are also a few other djFilteringSelect attributes I have tried like "Autocomplete" and "trim" but it does not work
Here is the code
<xe:djFilteringSelect id="test" type="select" store="jsondata" searchAttr="data" required="false" labelType="html" invalidMessage="Not valid">
<xe:this.dojoAttributes>
<xp:dojoAttribute name="required" value="false"></xp:dojoAttribute>
</xe:this.dojoAttributes>
</xe:djFilteringSelect>
Initally the field is not required, but if the user have entered a value it is required.
My question is if there a way to prevent the djFilteringSelect control to always populate the field if I have previously added a value
I found someone who solved this in another stack overflow topic, by creating an empty entry in my data store. but I could not get this to work
Dojo: Select of empty value for FilteringSelect while required=false
I do this quite a lot. Right now I don't have a working sample to show you (since I moved to bootstrap - and have to code the selects by manually adding select2 controls) but something like this should do it...
I add an "empty" value at the top of my select - and that seems to work no matter whether I am using a combobox, djCombobox or combobox with select2 from bootstrap. My markup typically looks like:
<xp:comboBox id="inputLocationSelector" value="#{User.catchListType}" disableClientSideValidation="true">
<xp:selectItem itemLabel="(none)" itemValue=""></xp:selectItem>
<xp:selectItems>
<xp:this.value><![CDATA[${Configuration.meta.listLocationTypeOptions}]]></xp:this.value>
</xp:selectItems>
</xp:comboBox>
Then you could specify "(none)", "All" or " " for the "not-selected" value depending on your needs.
Validation is a different thing so just specifying "required=false" does not give you the "empty" value.
/John

Spring bean comma separating values, but I want to overwrite

Alright, so I'm pretty new to Spring, but I was asked to resolve a bug. So in our application, we have a page that queries a database based on an id. However, not all entries are unique to the id. The id and date pair, on the other hand, do define unique entries.
So this page takes in an id. If there is only a single entry related to this id, everything works fine. However, if there are multiple entries, the page displays a radio button selection of the various dates that pertain to that id. We use something like:
< form:radiobutton id="loadDate" path="loadDate" value="${date}" label="${date}" />
Later on the same page, we want to display the data for that option. As part of it, we display the date of that selection:
< form:input id="aiLoadDate" path="loadDate" maxlength="22" size="22" class="readonly" readonly="true"/>
The problem is that when this happens, the variable (or bean? I'm not quite sure about Spring yet..) loadDate (a string) ends up being the same date twice, seperated with a comma. I'm guessing the problem here is the "path="loadDate"" that is common to both lines.
Instead of appending the date to the already existing one like a csv, I'd like it to overwrite the current entry intead. Is there a way to do this?
Spring is not the direct cause of your problem. When the elements of an HTML form are submitted, each element will appear in the request as a name=value pair. If two or more elements in the form have the same name (not id, name attribute) then those elements appear in the request as name=value,value (with one value per element with a duplicated name).
Option 1: stop using an input as a display element. Just display the date in a span (or div or paragraph or what ever). If you want the look of an input box (border, etc.) use CSS to create a class that has the look you want and attach the class to the span (or div or paragraph, etc) in which you display the date.
Option2: continue using an input as a display element. Disabled input elements are not added to the request when the form is submitted. in the form:imput set disabled="true".