asp.net mvc - DTO not picking up incorrect input - c#

I have a basic DTO object which I am trying to update, I noticed if I post some data from the UI to the controller and I enter string inside a decimal field the data annotations validation does not pick this up, in fact the string is converted into 0 for some reason...
How do I get my decimal values to remain decimal i.e. throw an error if a string is added, do I need to create a custom value provider for this DTO object?
My DTO:
public class FeesDTO
{
public int ID{ get; set; }
//[DataType( DataType.Currency)]
//[DisplayFormat(ApplyFormatInEditMode=true)]
public decimal ClientFee { get; set; }
public string VAT { get; set; }
public string GrossProfit { get; set; }
}
If I want to update my fees and I enter 'something' inside the ClientFee field this turns the string input into 0...
NOTE:
The commented out data annotations did not work... Is this the correct way to do this?

when you enter a string value e.g "xyz" for ClientFee which is a decimal variable, it can not be converted to decimal and you will get 0 as value of clientfee but when form is rendered again you will see validation message telling you that
xyz is not valid for field clientfee
this is perhaps due to the fact that when modelbinder fail to convert xyz to decimal it adds the error in Modelstate dictionary's error collection. you can make this value string in your viewmodel and validate it yourself using regex and when you are to store it to db you can convert it to your entity with AutoMapper to similar utility.

I think you need to be using the Data Annotation validators:
http://www.asp.net/mvc/tutorials/validation-with-the-data-annotation-validators-cs
Implement one on the Decimal field that throws a validation error if the Control is posted to with a non decimal entry.

Related

Plugin.CloudFirestore.Attribute converting a list of enums to their name value in Firestore

I am using the Plugin.CloudFirestore library for Xamarin. I have a model and would like to convert the enum to words when saving to my Firestore account. This works fine in most cases. The case I am having problems with is when I have a List of enums in my model. In this case I see a list of integers when I look at the Firestore database.
Here is a piece of my model class:
public class ExampleModel
{
[MapTo("name")]
public string Name { get; set; }
// This maps correctly with the name value of the enum
[MapTo("geneticType")]
[DocumentConverter(typeof(EnumStringConverter))]
public GKind GeneticType { get; set; }
// The list of these enums is not named correctly. The integer
// value of enum is shown in the list in the firestore database
[MapTo("produces")]
[DocumentConverter(typeof(EnumStringConverter))]
public List<UseKind> Produces { get; set; }
So how can I do this? I am thinking I need to pass in a second parameter into the DocumentConverter but I am unable to find any examples online on how to do this.
Thanks.

MVC3 Range attribute - doesnt admit value zero

I have the following attribute on my field:
[Range(-1,200)]
public decimal MyValue{ get; set; }
If I enter any value that doesn't fall in the range I get:
The field must be between -1 and 200
This is fine.
Here's the problem, I'm getting "The field must be a number" validation message when I enter zero which is a valid value.
Any suggestions?
Thanks
I think this may be happening due to the decimal type. Try this:
[Range(typeof(Decimal),"-1", "200")]
public decimal MyValue{ get; set; }
Source.

WebAPI, JSON.Net and losing decimal precision

I've come across a bit of a strange issue using WebAPI and JSON.Net. When de-serialising JSON that has been submitted to my API I seem to be losing precision! I'm submitting the decimal to 3 decimal places, but when the values materialises in my object it's only to 2 decimal places!
The JSON I submit looks like this:
{
id: 1,
name: 'mock data',
value: 123.456
}
This is bound to a class that looks something like this:
public class MockObject {
public int Id { get; set; }
public string Name { get; set; }
public decimal Value { get; set; }
}
Just for completeness this is basically what my WebAPI method looks like:
public HttpResponseMessage Post (MockObject data) {
// do something with the value here and return the relevant response
}
I'm submitting the data via a JQuery ajax request, but I can see the posted values are exactly as I expect when inspecting the values in the chrome dev tools before submitting and in fiddler once they've gone "over the wire".
When it gets to doing something with the materialised object in the Post method the value of "Value" is 123.45.
If I submit 2 or fewer decimal places (i.e. 123.4 or 123.45) the value gets de-serialised as expected, however if I submit more than 2 decimal places (i.e. 123.456 or 123.4567 etc the value is always getting de-serialised to 123.45.
Anyone else come across this issue? Any suggestions?
I managed to sort this out.
In the end the problem was being caused by the fact that the culture was being set which contains currency number formatting. The currency number format specifies the number of decimal places which should be used for decimal values.
To fix this I now set the WebApi JSON serializer culture to a new instance of CultureInfo.InvariantCulture in Global.ascx.cs like so:
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.Culture = new CultureInfo(string.Empty) {
NumberFormat = new NumberFormatInfo {
CurrencyDecimalDigits = 5
}
};
This means that decimal values can have anything up to 5 decimal places.

Problem getting the MVC3 model binder to bind to a decimal instead of an int

I have a AJAX call from my webpage sending the following data to my MVC3 action method.
{
"name":"Test",
"newitems":[
{"id":15,"amount":100,"unit":"gram"},
{"id":1,"amount":75,"unit":"gram"},
{"id":46,"amount":25,"unit":"gram"}
]
}
In my controller I have the following classes:
public class NewDataItem
{
public string name { get; set; }
public List<NewDataItemDetails> newitems { get; set; }
}
public class NewDataItemDetails
{
public int id { get; set; }
public int amount { get; set; }
public string unit { get; set; }
}
And the Action method that received the request have a NewDataItem as a parameter. This works perfect, however the amount property of NewDataItemDetails might not always contain an int. It might for example be 50.45. So because of that I changed the line public int amount { get; set; } to public decimal amount { get; set; }.
After this change amount is always shown as 0, and not the proper value that it did when it was an int.
Why does MVC fail to bind the value to the property when it is a decimal, when it worked just fine as an int?
See the answer here Default ASP.NET MVC 3 model binder doesn't bind decimal properties from ryudice about creating a DecimalModelBinder. It works and it also keeps all the model validation working, (some other solutions use deserialization which can stop validation from working.
I found the problem.
If I change the line "amount":100, to "amount":"100", it works fine. It seems that the MVC ModelBinder can manage the string to decimal conversion, but not the int to decimal.
Your type (class) NewDataItemDetails property amount is of type int.
You are making things difficult to manage. If you are expecting to have amount as a decimal eventually, it simplifies to actually use amount's type as decimal.
This will avoid having you to extend the default model binder and cater for your behaviour.
I think, it is wiser and it simplies to send the amount as decimal in the ajax call. it provides consistency.
I know I am a bit late with this but there is another solution which works without changing anything until MVC fixes it (I believe it is at their end).
In my javascript I add 0.00001 to my value if it is supposed to be a decimal but is a round number. For those I know should be currency values I know this has no effect and will round down. For those that I do not know their value and this could affect it I remove the 0.00001 from the value after binding in mvc. The binding works correctly as this is no longer an int in the eyes of mvc
If you don't want to change model binder then you can create json object and convert amount to string.It will work fine for me.
var test={"amount":""};
var test1={"amount":100}
test.amount=test1.amount.toString();

asp.net mvc int property bind exception

I have a int property in my class and want to validate if the user has entered a string.
How can I do that using data annotations?
When I pass a non-integer value I get a excpetion like this:
The value 'asdasd' is not valid for property.
For example using this validation attribute:
[Range(0, Int32.MaxValue, ErrorMessage="Invalid Number")]
public int? Number { get; set; }
and entering 'aaa' in a field tha uses the model I've got an excepetion with this message:
The value 'aaa' is not valid for Number.
Instead of the "Invalid Number" message.
Any Ideas?
I've put
[Range(0, Int32.MaxValue, ErrorMessage="Invalid Number")]
public int? Number { get; set; }
but I've got this message from an excpetion
The value 'aaa' is not valid for Number.
There are two stages of validation at play here.
Before the validation set up in your attributes is called, the framework first attempts to parse the information.
So here are a couple of examples based on this code:
[Range(0, Int32.MaxValue, ErrorMessage="Invalid Number")]
public int? Number { get; set; }
I type nothing into the box...
"Invalid Number" (Framework will create a null integer, your validation rule fails)
I type "A" into the box...
"The value 'A' is not valid for Number." (Framework cannot convert "A" into a nullable int, so the framework validation rule fails and your validation rule it not checked.
** Solutions **
1 - Live with the default message until you are using MVC 3 / .NET 4, which makes it easier to override these messages
2 - Exclude the value from the binder, so it won't cause an error (but you will have to bind it and check it yourself)
[Bind(Exclude="MyNumber")]
3 - Make it a string on the model, then test it with a TryParse and add your own custom model error (This is a reasonable practice and reminds us all why View Models are used rather than Domain Objects!)
if (!Int32.TryParse("MyNumber", out myInteger)) {
ModelState.AddModelError("MyNumber", "That isn't a number!");
}
There are actually lots of solutions, but I would say go with option 3 for now.
You could put a Range-attribute on your model-field like so:
[Range(0, 9999)]
public int Something {get; set;}
Now whenever the user inputs a string it will not validate, and also the int must be between 0-9999
this should also work with
[Range(0, 9999)]
public string Something {get; set;}
and
[Range(0, 9999)]
public object Something {get; set;}

Categories