Firefox is caching hidden inputs even with autocomplete turned off - asp.net-mvc-3

I have a form with the autocomplete attribute set to off.
Inside this form, there is a hidden input element (generated using ASP.NET MVC's Html.HiddenFor() method, but, that should be irrelevant):
<input type="hidden" value="0" name="Status" id="Status" data-val-required="The Status field is required." data-val-number="The field Status must be a number." data-val="true">
When the form is submitted, this value is incremented by one and the model is returned to the view. If I write the status value to the page, I can see that the value was correctly incremented.
However, this hidden input field is always cached. It's never getting the correct value. I tried setting the autocomplete attribute directly on the input element, but without success.
How can I get this hidden field to get the correct value? I'd prefer not to use any Javascript.
Edit: Supplying more code...
Controller
//This code is being executed, and the status is being incremented.
shippingOrder.Status = (shippingOrder.Status != (int)OrderStatus.Closed) ? shippingOrder.Status + 1 : shippingOrder.Status;
View
#using (Html.BeginForm("Number", "Order", FormMethod.Post, new { id = "orderSummary", autocomplete = "off" })) {
...
#Html.HiddenFor(m => m.Status)
}

According to this post here html helpers such as HiddenFor will always first use the posted value and after that the value in the model.
As you said, when writing the value to the page you can see it incremented, yet the helper is using the previously posted value, which is the intended behaviour.
The link does suggest the use of ModelState.Remove("Status") or ModelState.Clear() before assigning the new value.
It also suggest that another option could be not using a HiddenFor helper but instead to build the hidden field yourself. Similar to this:
<input type="hidden" name="Status" value="#Model.Status" />
Either way it looks like your problem is based on similar circumstances.

Related

MVC matching ModelState keys to ViewModel collection

Is it possible to match a ViewModel property to the matching ModelState.Key value when the ViewModel is a (has a) collection?
Example: To edit a collection of viewmodel items, I am using the extension found here.
That adds a GUID to the id of the fields on the page.
example:
class Pets
{
string animal;
string name;
}
For a list of Pets, the generated html source is like this:
<input name="Pets.index" autocomplete="off" value="3905b306-a9..." type="hidden">
<input value="CAT" id="Pets_3905b306-a9...__animal" name="Pets[3905b306-a9...].animal" type="hidden">
<input value="MR. PEPPERS" id="Pets_3905b306-a9...__name" name="Pets[3905b306-a9...].name" type="hidden">
<input name="Pets.index" autocomplete="off" value="23342306-b4..." type="hidden">
<input value="DOG" id="Pets_23342306-b4...__animal" name="Pets[23342306-b4...].animal" type="hidden">
<input value="BRUTICUS" id="Pets_23342306-b4...__name" name="Pets[23342306-b4...].name" type="hidden">
So when this gets bound on post, the ModelState gets loaded with all the form fields.
In ModelSTate.Keys, there is:
Pets[23342306-b4...].name
Pets[23342306-b4...].animal
Pets[3905b306-a9...].name
Pets[3905b306-a9...].animal
Everything good so far, but I am doing some business logic validation, things like, cant add new animal if one exists with the same name. In that case, I want to be able to highlight the input field that is in error.
So if my create function fails, it will return an error/key value pair like this:
{ error = "Duplicate Name", key="name" }
So I at least will now what property caused the problem.
But since my repository functions don't know about the view field ids, how can I match the key "name" to the appropriate ModelState key (in this case, either Pets[23342306-b4...].name or Pets[3905b306-a9...].name)?
If you used the built in functionality of MVC for displaying collections (Html.DisplayFor(m => m.Pets) or Html.EditorFor(m => m.Pets)) with appropriate display/editor template, MVC would render something like this:
Pets[0].name
Pets[0].animal
Pets[1].name
Pets[1].animal
This maps to IEnumerable<Pets> and you know that first item has index of 0, second item 1 etc.
So if the second item has an error, you can set error for the ModelState key "Pets[1].name" for example.
If you are using the Html.BeginCollectionItem extension method, like I was, I was able to get around this by not using the GUID. I need the dynamic add and delete, but I was always looking up known items, persons that have an ID, which I had in my editor. So instead of using the GUID, I just assign the ID (uniqueId) in the code below. I could then find the key because I knew it was Person[234232]. Of course if you are adding new items and not displaying selected items, it might not work for you.
public static IDisposable BeginCollectionItem(this HtmlHelper html, string collectionName, string uniqueId)
{
var idsToReuse = GetIdsToReuse(html.ViewContext.HttpContext, collectionName);
string itemIndex = idsToReuse.Count > 0 ? idsToReuse.Dequeue() : uniqueId;
// autocomplete="off" is needed to work around a very annoying Chrome behaviour whereby it reuses old values after the user clicks "Back", which causes the xyz.index and xyz[...] values to get out of sync.
html.ViewContext.Writer.WriteLine(string.Format("<input type=\"hidden\" name=\"{0}.index\" autocomplete=\"off\" value=\"{1}\" />", collectionName, html.Encode(itemIndex)));
return BeginHtmlFieldPrefixScope(html, string.Format("{0}[{1}]", collectionName, itemIndex));
}

Validate a Hidden Field

I'm using MVC3 with unobtrusive validation. I have a field that the user is expected to fill with some data and then press a "search" button. If search has never been pressed or the user has changed the input field after pressing search, the form should not be possible to submit.
I've added a hidden field that is set to true by the click() event of the button and emptied by the keyup() event of the input box. Now I would like to add a validation rule that requires the hidden field to be true to allow submit.
Preferably I would like to use unobtrusive validation, but if that doesn't work it is ok with something that requires some javascript, as long as it doesn't spoil the unobtrusive validation for the rest of the form.
The following code snippet does exactly what I want, until I add type="hidden".
<input class="required" id="client-searched" data-val="true"
name="ClientSearched" data-val-required="Press search!"/>
<span class="field-validation-valid" data-valmsg-replace="true"
data-valmsg-for="ClientSearched"/>
try
var validator = $("#myFormId").data('validator');
validator.settings.ignore = "";
Here is an informative blog post
EDIT
#RAM suggested a better solution please FOLLOW
I had a similar problem, and I used this code to change defaults, in MVC 4:
#Scripts.Render("~/bundles/jqueryval")
<script type="text/javascript">
$.validator.setDefaults({
ignore: ""
})
</script>
Source:
JQuery validate
In some cases you want just ignore validation on one or several
hidden fields (not all hidden field) in client side and also you want validate them and other hidden fields in server side.
In these cases you have validation attributes for all hidden fields in your ViewModel and they will be used to validate the form when you post it (server side).
Now you need a trick to just validate some of the hidden fields in client side (not all of them). In these cases i recommend you to use my mechanism!
Set data-force-val as true in the target hidden input tags. It's our custom attribute that we use to detect target hidden inputs witch we want validate them in client side.
// This hidden input will validate both server side & client side
<input type="hidden" value="" name="Id" id="Id"
data-val-required="The Id field is required."
data-val="true"
data-force-val="true">
// This hidden input will validate both server side & client side
<input type="hidden" value="" name="Email" id="Email"
data-val-required="The Email field is required."
data-val="true"
data-force-val="true">
// This hidden input just will validate server side
<input type="hidden" value="" name="Name" id="Name"
data-val-required="The Neme field is required."
data-val="true">
Also you can set data_force-val for your hidden inputs by jQuery:
$("#Id").attr("data-force-val", true); // We want validate Id in client side
$("#Email").attr("data-force-val", true); // We want validate Email in client side
$("#Name").attr("data-force-val", false); // We wont validate Name in client side (This line is not necessary, event we can remove it)
Now, active data-force-val="true" functionality by some simple codes like these:
var validator = $("#TheFormId").data('validator');
validator.settings.ignore = ":hidden:not([data-force-val='true'])";
Note: validator.settings.ignore default value is :hidden

Posting an array of Guid pairs to an Action

As you can see here, I'm allowing a user to dynamically create a table of data, and storing the ids of the table in a hidden field (in the example it's a text area so you can see it, and the final solution will be Guid rather than integers).
My question is simply this: What data type should I use on the server/MVC action to take the data held in the textarea/hidden field?
At the moment I have a string, and am contemplating doing a load of .split()'ing and whatnot, but it doesn't feel right!
Ultimately I need some sort of IEnumerable<Guid, Guid> thing?!?! so I can do a foreach and get each pair of Ids.
I'm sure the answer will be simple, but I can't think of what to do.
Any help appreciated.
If your UI has multiple, like-named form fields, they will be submitted to your action method and bound properly to an array. We could use string[] for this case.
<form action="">
<input type="text" name="guids"/>
<input type="text" name="guids"/>
<input type="text" name="guids"/>
<input type="text" name="guids"/>
<input type="submit" value="Submit"/>
</form>
Then your controller could handle them like so:
public ActionResult MyAction(string[] guids)
{
guids.Count == 4 // if all four fields were filled in.
}
Note that if there is just a single guids value sent by the form, the string[] guids will still work - it will contain just a single item.
Finally, note that if no values are entered, the array value will be null, not an empty array.
You can actually bind to a list from your model, take a look at this post
http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx

Client side validation not working for hidden field in asp.net mvc 3

I have got a hidden field with a validation for it as below
#Html.HiddenFor(m => m.Rating)
#Html.ValidationMessageFor(m => m.Rating)
The Rating property has Range validator attribute applied with range being 1-5. This is put inside a form with a submit button.
I have then got following jquery that sets the value in hidden field on some user event (Basically user clicks on some stars to rate)
$(".star").click(function(){
$("#Rating").val(2);
});
Now if I submit the form without the user event that sets the hidden field, the validation works. The error messages is displayed properly and it works all client side.
Now, in this situation, if I click on stars, that invokes the above javascript a sets the hidden field, the validation error message would not go away. I can submit the form after the hidden variable has some valid value. But I'm expecting that the client side validation should work. (When the hidden variable has been set with some valid value, the validation error should go away)
Initially I thought, the jquery validation would be invoked on some special events so I tried raising click, change, keyup, blur and focusout events myself as below
$(".star").click(function(){
$("#Rating").val(2);
$("#Rating").change();
});
But this is still not working. The error messages once appeared, does not go away at all.
You can wrap your hidden field with a div put somewhere but still inside the <form>. Add css to kick it to outer space.
<div style="position:absolute; top:-9999px; left:-9999px">
<input id="Rating" type="hidden" name="rating" >
</div>
Then add the following label to where you want to show the error:
<label for="rating" class="error" style="display:none">I am an an error message, please modify me.</label>
Client-side validation ignores hidden fields. You can set the "ignore" option dynamically but just to get it to work I did the following directlyl in the .js file.
For now this should do the trick.
In my aspx...
<%: Html.HiddenFor(model => model.age, new { #class="formValidator" }) %>
In jquery.validate.js
ignore: ":hidden:not('.formValidator')",
This turned out to be a very interesting issue. the default "ignore" setting is ignores hidden fields. The field was hidden in a jQuery ui plug-in. I simply added a class called "includeCheckBox" to the rendered input I wanted to validate and put the following line of code in...
var validator = $('#formMyPita').validate();
validator.settings.ignore = ':hidden:not(".includeCheckBox")';
if ($('#formMyPita').valid()) {....
In the code which sets the hidden field's value, manually invoke validation for the form, like so:
$("form").validate().form();
I think it is because hidden inputs don't fire any of these events.
What you could do instead would be to use a <input type="text" style="display:none" /> instead of the hidden field;
#html.TextBoxFor(m => m.Rating, new {display = "display:none"})

Using unobtrusive validation works on individual elements but not the whole form

Using Asp.Net MVC3 with unobtrusive validation. I have a form that has a few input fields. One of the fields is pretty simple:
<input id="Name" class="valid" type="text" value="" name="Name" data-val-required="Enter your name." data-val-length-min="5" data-val-length-max="50" data-val-length="Enter a valid name." data-val="true">
I then have some js that validates the form and submits it only if client-side validation passes as in:
var $form = $('#contact_form');
var formAction = $form.attr('action');
var serialized = $form.serialize();
if ($form.validate().valid()) {...
Now the last line always returns true (yes I have unobtrusive enabled). However if I change the last line to:
if ($form.validate().element('#Name')) { ...
It works great and returns false. I have many fields and don't want to iterate over each one and am confused as to why when validating the whole form it says true but validating each individual element returns false correctly.
Things I tried:
- reparsing the the form via unobtrusive's $.validator.parse(... to no avail. It's not a dynamic form and gets rendered when the page loads.
Note: I also checked that jquery (v1.6.2) jquery.validate.min.js (v1.8.1) and jquery.validate.unobtrusive.min.js are loaded in the browser.
You don't have to call .validate() but directly .valid():
if ($form.valid()) {
...
}

Resources