I have a question about (Clientside?) validation of datafields.
My model has a decimal property
public decimal CalculatedWork { get; set; }
If I try to insert a decimal value like 20,00 I get an error "Value has to be numeric".
If I insert 20, everything is fine and when refreshing, 20,00 is shown.
How can I get this work?
I tried This DataFormatString and this DecimalModelBinder but nothing works.
The DecimalModelBinder isn't even hit.
What can I do or where is my fault?
Related
In my code-first entity framework sql database I have a decimal value specified as 18,3.
Database object:
public decimal? Kolhalt { get; set; }
In OnModelCreating I have
modelBuilder.Entity<Skada>().Property(o => o.Kolhalt).HasPrecision(18, 3);
In the database the value is specified as Kolhalt (decimal(18, 3), null)
If I enter a value directly in the database I get three decimals, but when I insert or update a value with EntityFramework it is truncated to 2 decimal places.
With Sql server profiler I can see that EF specifies 2 decimals for the stored value:
[Kolhalt] = #14 ... #14 decimal(18,2) ... #14=5.12
(The entered value was 5.123).
So for some reason EF truncates the values sent to the database when I call SaveChanges().
Do I have to specify the number of decimals someplace else to get it right in SaveChanges()?
Best regards,
Henrik
I had a similar problem in a project. Oddly, when I changed my model from decimal? to decimal it started working. I also found a configuration setting TruncateDecimalsToScale which can be added:
public class DbContextConfiguration : DbConfiguration
{
public DbContextConfiguration()
{
var providerInstance= SqlProviderServices.Instance;
SqlProviderServices.TruncateDecimalsToScale = false;
this.SetProviderServices(SqlProviderServices.ProviderInvariantName, SqlProviderServices.Instance);
}
}
I did some research about this problem, but NOTHING comes close to MY difficulty.
Here's my SQL :
CREATE TABLE [dbo].[Departement] (
[IdDepartement] INT IDENTITY (1, 1) NOT NULL,
[Description] NVARCHAR (255) NOT NULL,
[IsActif] BIT NULL,
PRIMARY KEY CLUSTERED ([IdDepartement] ASC)
);
As you can see, IsActif IS null.
Here's part of my Departement.cs :
public Nullable<bool> IsActif { get; set; }
Once again, everything is normally nullable.
Here's part of my Metadata (for not loosing the annotations when the database is updated) :
[UIHint("YesNo")]
public Nullable<bool> IsActif { get; set; }
Still, a nullable force of the nature, without [Required]! (If someone wonders what is a UIHint: it is connected to a DisplayTemplate and it just presents nicely my bit value).
Just for the curious ones, because I feel my question will not be complete if I do not put everything in here. Here's my UiHint:
#model Nullable<bool>
#if (Model.HasValue)
{
if (Model.Value)
{ <text>Oui</text> }
else
{ <text>Non</text> }
}
else
{ <text>Indéfini</text> }
It clearly states if Model Has Value ON Nullable!!!
But this is what I get when a try to Create a new department:
which means 'the field IsActif is required.'
Someone has an idea what is going on? All my other nullable booleans work perfectly. Is there's a place I forgot to look? What's the next step?
If someone have an idea, please let me know. I did pet my computer to make this work, but I am about to eat it now.
Thanks in advance.
Edit
Mea Culpa: Oooooooooh, I so want to die. I just realised I was using a ViewModel and I should check there. And there it was, the culprit looking at me with a devilish snigger. I am sorry for this newbie mistake and for my punishment, I will close this question and mark it as answered and leave it here for everybody to laugh at me and just in case another newbie have the same problem. I still do not understand why my others nullable boolean worked, while they were in the same situation, though...
Just go see my Edit. I am too shameful to repeat it here. Thanks anyway to those who took their time to add comments, specially Jasen.
In big:
EmployeViewModel before:
public bool IsActif { get; set; }
EmployeViewModel after:
public Nullable<bool> IsActif { get; set; }
Now I just have to hide myself under a carpet.
We were getting a NullReferenceException from line 135 until I added the if statement on line 134.
It shouldn’t have been necessary because of the check on line 124.
I couldn’t reproduce it locally. But it happened every time on live for certain scenarios. This extension method is called from the SearchResultsViewModel constructor, but I wouldn’t think that would matter.
Am I missing something obvious?
This is how I call the extension method
ParseParentCategory(SearchKey)
This is how the SearchResultsViewModel is defined
Public Class SearchResultsViewModel
Inherits ViewModelBase
Public ReadOnly _ConstructedProperly As Boolean
Public Property SearchKey As String
Public Property ParentCategoryId As Integer = -1
Public Property ParentCategoryName As String
Public Sub New(Request As HttpRequestBase, pPartiallyPopulatedStupidInputModel As SearchResultsViewModel, pSearchBy As IProductsSearch.SearchBy)
I'm developing a Login View in MVC5.
I would like to set at the ViewModel level a DataAnnotation to state the the field does NOT accept empty spaces.
Is there a Data Annotation in MVC (something like [NoSpaces] that can be used to NOT allow a string field to contain "spaces" ?
How about this:
[RegularExpression(#"^\S*$", ErrorMessage = "No white space allowed")]
Well, the simplest but robust thing I can think of is to look at how existing code works, or how existing data annotation work.
For example, let's look at the System.ComponentModel.DataAnnotations.StringLengthAttribute class.
Here's the definition only (just to keep short):
namespace System.ComponentModel.DataAnnotations
{
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)]
public class StringLengthAttribute : ValidationAttribute
{
public StringLengthAttribute(int maximumLength);
public int MinimumLength { get; set; }
public override string FormatErrorMessage(string name);
public override bool IsValid(object value);
}
}
So I would simply copy the original implementation source code from GitHub and customize it to my needs. For example, to obtain a signature like this (if I understood correctly and this is what you wanted):
public StringLengthAttribute(int maximumLength, int minLength = 0, allowEmptySpaces = true);
For more in-depth info, I would also read the Microsoft docs on the ValidationAttribute class, which is your base class for custom validation data annotations.
EDIT:
I would NOT rely on Regular Expressions to validate data in cases where I just need to exclude empty strings or strings containing only white space(s), because Regular Expressions are very expensive to process (and require a lot of memory allocation, because of an expression compiler, a state machine, etc.).
If this is convenient for anyone, I got pass this issue by doing this on the client:
//trim each form input
var $form = $("#myForm");
$form.find("input:text").each(function(){
var $self= $(this);
$self.va($self.val().trim());
});
//then validate before submit
if($form.valid()){ $form.submit(); }
// on the server ModelState.Isvalid does verify each item with [Required] and won't accept only white spaces from an input (but this means additional roundtrip to server and it's not always convenient)
I have a MVC4 application with unobstrusive javascript client-side validation. This is working fine except for decimal validation. I am encoutering some strange and annoying behaviour.
The decimal validation only allows numbers with three numbers after the decimal separator. However i want this to work with two numbers after the separator (or just any number is fine as it should do by default if i'm correct).
so 1.222 is valid and 1.22 and isn't while i wan't it to be valid. (1.2222 is neither valid).
in my view i have a normal:
#Html.TextBoxFor(x => x.BasePrice)
my model:
[Required]
public decimal BasePrice { get; set; }
and my controller:
ProductVM model = new ProductVM()
{
BasePrice = product.BasePrice
};
product is an Entity Framework 4 entityobject
I've also tried putting;
[DisplayFormat(DataFormatString = "{0:n2}", ApplyFormatInEditMode = true)]
in my model. But this doesn't work either. It has no effect.
I've never seen any behaviour like this when working with MVC. I have no idea where to look. Any clues?
I still don't know what the problem is, but I fixed it with a little bit dirty workaround:
$.validator.methods.number = function (value, element) {
if(!isNaN(parseFloat(strValue)))
{
return true;
}
return false;
}
by overriding the client side decimal validation. just added this in a script block in my _layout.cshtml.
server side validation will ensure the security is still ok by complete validation.