ASP NET MVC 3: Form doesn't POST due to a required hidden field - asp.net-mvc-3

I want to submit a form, but the button isn't clickable. After some search I found out that this is due to the jquery validation that ASP.NET MVC has for required fields.
For some weird reason ASP NET thinks my hidden field "UserId" is required. Which isn't actually true. See part of my model here:
public class ResetPasswordModel
{
[.....]
public Guid UserId
{
get;
set;
}
}
And the page source shows this:
<input data-val="true" data-val-required="The UserId field is required." id="UserId" name="UserId" type="hidden" value="" />
Any ideas?!?

The fact it's not a nullable type means it's required. Change the definition to Guid? (include the question mark to make it nullable) Or even better create a viewmodel that doesn't have it.

I believe that a Guid is required by default because it is not nullable. Guids are usually primary keys so making them nullable is problematic. Try converting your guid ToString() so that you can use it in your view, then back to a Guid before using it in your controller or model. You may have to create a ViewModel in order to do this.

Are you sure there isn't a separate partial class containing MetaData which has marked the field as mandatory?
Something like this:
class UserResetPasswordModelMetaData
{
[Required(ErrorMessage = "The UserId field is required.")]
public Guid UserId { get; set; }
}
Search your project for the string "The UserId field is required". I bet it's there somewhere.
Also, how do you identify the user who is trying to reset their password, if not by their id?

setup the jQuery validator to ignore hidden fields. Like so:
jQuery Validate Ignore elements with style

Probably There is a Key attribute on top of UserId property which means it's mandatory

Related

Automatical bind of datetime fields in MVC3

I have a page with many date fields, which can be dynamically added on client side. I have a DatTime? property on editor template for this field:
[Display(Name = "Bar Admission Date")]
public DateTime? AdmissionDate { get; set; }
When I'm submitting a form I get a null data in AdmissionDate field because binder doesn't know the format of the field.
I have 2 ideas of how t oovercome this issue:
Make a string field in model and parse it on a server side. Simple and pretty quick.
Write a custom model binder for date fields. I don't like this solution because I don't know the keys for all fields that I will use.
Is there better solution? I searched how can I overload TextboxFor method in order to pass it a culture, but I didn't find
Sounds like you should use an enumerable (IList/ICollection) of DateTime?. Phil Haacked has a good article on model binding to a list (even when the number of items is dynamic).
Updated
As for the formatting problem, I would look at how to set the culture for the project/model binder.

DropDownList Client Side Validation is validating when it should not be. (MVC3, Razor)

I am still learning MVC3 and Razor, so this is perhaps a simple question.
On a view I have a DropDownList whose sole purpose is to help filter (via AJAX) a second drop down list:
#Html.DropDownList("Segments", "-- select segment --")
There is a Segments property of the ViewModel that is defined as:
public IEnumerable<SelectListItem> Segments { get; set; }
There is JavaScript that handles the change event for this DropDownList and populates another DropDownList with appropriate values. That other DropDownList is defined like this:
#Html.DropDownListFor(m => m.fafhProdRecId, Enumerable.Empty<SelectListItem>(), "-- select product recommendation --")
This all works fine until I submit. When I submit, I get a validation error on the Segments drop down list!
Now -- there should be absolutely NO validation on the segments DropDownList -- there shouldn't be any client side validation on EITHER drop down list, for that matter.
But when I try to submit, I get the validation error message back:
The value '1' is invalid.
I have no idea why this is happening.
I have no idea how to decorate the Segments property to say that it is NOT required.
I have no idea how to tell the unobtrusive javascript validator that it is, in fact, being quite obtrusive.
In your ViewModel class add [Bind(Exclude = "Segments")]
From: Using Data Annotations for Model Validation
make sure that your Model has fafhProdRecId as nullable, I imagine it's declared as:
public int fafhProdRecId { get; set; }
change this to:
public int? fafhProdRecId { get; set; }
hopefully, that should resolve the issue as this effectively makes the model field nullable (assuming the db field IS nullable too of course).

MVC3 Required validation, choose value for empty

I have a hidden field which is bound to a int Id in the model, it has a required attribute and some fancy ajax code to set the id client side, the problem is that zero should be acounted as empty. Now the validation will succeed even if no Id has been selected, bow can I set which value should be counted as empty? I hope i do not need to create a custom validator for it.
Thanks
It doesn't maker sense to add required attribute to a non nullable type such as Int32. Value types are always required. You could use a nullable integer instead:
[Required]
public int? SomeProperty { get; set; }

RIA service default required attribute

I have an EF4 model with table's columns doesn't allow null.
At the SL client application I always receieve the "columnName is required" because I have the binding in xaml with [NotifyOnValidationError=True,ValidatesOnExceptions=True] for the textboxes.
My questions is:
I can overide the default required errormessage at the metadata class, but how can I have it as a custom validation? I mean I don't wnat to do this at the sealed metadata class:
[Required(ErrorMessage = "Coin English Name Is required")]
[CustomValidation(typeof (CustomCoinVaidation), "ValidateCoinName")]
public string coin_name_1 { get; set; }
I want to have it inside the custom validation method that I will define for all types of errors regards that coin_name_1, as follows:
public static ValidationResult ValidateCoinName(string name, ValidationContext validationContext)
{
if (string.IsNullOrWhiteSpace(name))
{
return new ValidationResult("The Coin Name should be specified", new [] { "Coin Name" });
}
return ValidationResult.Success;
}
Why?
for two reasons :
1- Group all the validation isdie one container (for easy localization further).
2- I don't want the coin_name_1 to be displayed to the end-user, but a meanigful as "Coin English Name".
Second question:
I have a ValidationSummary control on my xaml page where all the errors are displayed but is displaying the orignal name of the column "coin_name_1" how can I chnge that to be a meanigfil also.
Best regards
Waleed
A1:
I just left the required as it is implemented right now..
A2:
I went through different sources and find this artical.
It shows how to style the validation summary:
http://www.ditran.net/common-things-you-want-know-about-silverlight-validationsummary
I am also implementing a client-side validation asyncronizly.
Regards

MVC 3, NHIbernate Validators & Message Interpolator

I have followed this article and have a passing test showing custom validation error messages being returned from a resource file when a call to Validator.IsValid(someEntity) fails.
I am trying to translate this to the new unobtrusive client-side validation in MVC3 describe by this article. This also more or less works - well the client-side validation does so I can assume my wiring of NHValidators is good, as you can see the following is output:
<input data-val="true" data-val-required="{NotNullNotEmpty}" id="Username" name="Username" type="text" value="" />
<span class="field-validation-valid" data-valmsg-for="Username" data-valmsg-replace="true">
My problem is that this time the CustomMessageInterpolator has not fired - the resource string has not been translated for this property (it's still in curly braces): {NotNullNotEmpty}.
Both my test and the web are usign the same NHValidator config:
var cfg = new FluentConfiguration();
cfg
.SetMessageInterpolator<CustomMessageInterpolator>()
.SetCustomResourceManager("MyProject.Core.Resources.ValidationMessages", Assembly.Load("MyProject.Core"))
.SetDefaultValidatorMode(ValidatorMode.UseAttribute)
.Register(Assembly.Load("MyProject.Core").ValidationDefinitions())
Just for good measure here's the model snippet:
public class LoginModel
{
[NotNullNotEmpty(Message = "{NotNullNotEmpty}")]
public string Username { get; set; }
Long shot I know but any ideas would be appreciated!
I had no luck with this having posted it around a few forums.
In the end I've resorted to using DataAnnotations instead in my View Models for client-side validation.
Of course this is really hacky and a horrible "solution" as I've now two types of validation attributes in my code. (if wondering, yes I'd rather keep my NH Validation attributes 1. as I'm still generating my schema from them and 2. I like the way NH validates before committing to the db i.e. server-side).
If interested, here's how to use resource files to show the correct labels for your controls.
This code snippet shows how to then also rig up custom error messages:
[DisplayResource(typeof(LabelResources))]
public class NewChildTagViewModel : ModuleViewModel
{
public int ParentId { get; set; }
[Required]
public string Title { get; set; }
[Range(1, 1000, ErrorMessageResourceType = typeof(ValidationMessages), ErrorMessageResourceName = "Display_Order")]
[Required]
public int? DisplayOrder { get; set; }
}
Can you show your code? I presume you used some sort of custom ModelValidatorProvider?
I've got something working like what you described. It required writing a custom AssociatedValidatorProvider and ModelValidator, along the lines described here
http://weblogs.asp.net/srkirkland/archive/2010/07/20/nhibernate-client-validator-asp-net-mvc-2-model-validation.aspx
but changing the MessageOrDefault method in the article above to use the NHibernate Validator DefaultMessageInterpolator to translate the messages.
It sounds like you got most of the way towards getting something working, and you just needed to use the DefaultMessageInterpolator to translate the messages.

Resources