How to validate type of collections?
How can I validate and catch collection type conversion (JSON string array to C# long collection) for my System.Web.Http.ApiController class (before the model is initialized if possible)?
I want to validate and catch any non-numeric elements in the JSON array to be return as a bad request response (maybe somehow with data annotation).
When non-numeric JSON elements are included (to be converted to long collection), they fail to parse and get stripped before the model is passed to the ApiController method. Given the classes below, a valid input should contain only numeric values for "PerferredNutTypes" and "GeographyIDs".
Classes
public class SquirrelController : ApiController
{
[HttpPost]
[Route("api/squirrels/search")]
[SwaggerResponse(HttpStatusCode.OK, Type = typeof(SquirrelsResponse))]
public HttpResponseMessage Squirrels(SquirrelsRequest model)
{
// model already parsed by the time breakpoint reaches here and non-convertable elements already stripped
...
...
...
SquirrelsResponse results = Targeting.SearchForSquirrels(model);
return Request.CreateResponse(HttpStatusCode.OK, results);
}
}
public class SquirrelsRequest
{
public SquirrelsRequest() {}
public List<long> PreferredNutTypes { get; set; } = new List<long>();
public GeographySearch geographySearch { get; set; } = new GeographySearch();
}
public class GeographySearch
{
public GeographySearch() {}
public BooleanOperator Operator { get; set; } = BooleanOperator.OR;
public List<long> GeographyIDs { get; set; } = new List<long>();
}
public enum BooleanOperator
{
AND,
OR
}
Examples:
//"Toronto" sould be an invalid input when converting from JSON string array to c# long collection.
{
"PreferredNutTypes": [34,21],
"GeographySearch": {
"Operator": 1,
"GeographyIDs": ["Toronto"]
},
}
// This is what the model currently looks like in public HttpResponseMessage Squirrels(SquirrelsRequest model)
new SquirrelsRequest()
{
PreferredNutTypes = new List<long>() { 34, 21 },
GeographySearch = new GeographySearch()
{
Operator = 1
GeographyIDs = new List<long>()
}
}
Expectations:
Things I've attempted:
System.Web.Http.Controllers.HttpActionContext actionContext.ModelState.["model.GeographySearch.GeographyIDs[0]"].Errors[0].Exception.Message => "Error converting value "sonali7678687" to type 'System.Int64'. Path 'subjectSearch.writingAbout[0]', line 6, position 36."
System.Web.Http.Controllers.HttpActionContext actionContext.ModelState.["model.GeographySearch.GeographyIDs[0]"].Errors[0].Exception.InnerException.Message => "Input string was not in a correct format."
... surely there must be a better way of validating?
UPDATE 1:
Rephrased question to make explanation and intent more clear.
c# asp.net asp.net-mvc data-annotations asp.net-apicontroller
add a comment |
How can I validate and catch collection type conversion (JSON string array to C# long collection) for my System.Web.Http.ApiController class (before the model is initialized if possible)?
I want to validate and catch any non-numeric elements in the JSON array to be return as a bad request response (maybe somehow with data annotation).
When non-numeric JSON elements are included (to be converted to long collection), they fail to parse and get stripped before the model is passed to the ApiController method. Given the classes below, a valid input should contain only numeric values for "PerferredNutTypes" and "GeographyIDs".
Classes
public class SquirrelController : ApiController
{
[HttpPost]
[Route("api/squirrels/search")]
[SwaggerResponse(HttpStatusCode.OK, Type = typeof(SquirrelsResponse))]
public HttpResponseMessage Squirrels(SquirrelsRequest model)
{
// model already parsed by the time breakpoint reaches here and non-convertable elements already stripped
...
...
...
SquirrelsResponse results = Targeting.SearchForSquirrels(model);
return Request.CreateResponse(HttpStatusCode.OK, results);
}
}
public class SquirrelsRequest
{
public SquirrelsRequest() {}
public List<long> PreferredNutTypes { get; set; } = new List<long>();
public GeographySearch geographySearch { get; set; } = new GeographySearch();
}
public class GeographySearch
{
public GeographySearch() {}
public BooleanOperator Operator { get; set; } = BooleanOperator.OR;
public List<long> GeographyIDs { get; set; } = new List<long>();
}
public enum BooleanOperator
{
AND,
OR
}
Examples:
//"Toronto" sould be an invalid input when converting from JSON string array to c# long collection.
{
"PreferredNutTypes": [34,21],
"GeographySearch": {
"Operator": 1,
"GeographyIDs": ["Toronto"]
},
}
// This is what the model currently looks like in public HttpResponseMessage Squirrels(SquirrelsRequest model)
new SquirrelsRequest()
{
PreferredNutTypes = new List<long>() { 34, 21 },
GeographySearch = new GeographySearch()
{
Operator = 1
GeographyIDs = new List<long>()
}
}
Expectations:
Things I've attempted:
System.Web.Http.Controllers.HttpActionContext actionContext.ModelState.["model.GeographySearch.GeographyIDs[0]"].Errors[0].Exception.Message => "Error converting value "sonali7678687" to type 'System.Int64'. Path 'subjectSearch.writingAbout[0]', line 6, position 36."
System.Web.Http.Controllers.HttpActionContext actionContext.ModelState.["model.GeographySearch.GeographyIDs[0]"].Errors[0].Exception.InnerException.Message => "Input string was not in a correct format."
... surely there must be a better way of validating?
UPDATE 1:
Rephrased question to make explanation and intent more clear.
c# asp.net asp.net-mvc data-annotations asp.net-apicontroller
1
TheModelState
errors are telling you want is invalid (i.e. in the example you gave, its telling you that the first value ofGeographyIDs
is invalid) so its not clear what you are expecting or want to do.
– user3559349
Nov 19 '18 at 22:15
I think you can get the current value fromRequest["GeographySearch.GeographyId"]
, but I would just look atModelState.Where(m => m.Errors.Count > 0)
and return a genericResponse.StatusCode = 404
if the result is not null to keep it simple.
– Kristianne Nerona
Nov 20 '18 at 0:16
add a comment |
How can I validate and catch collection type conversion (JSON string array to C# long collection) for my System.Web.Http.ApiController class (before the model is initialized if possible)?
I want to validate and catch any non-numeric elements in the JSON array to be return as a bad request response (maybe somehow with data annotation).
When non-numeric JSON elements are included (to be converted to long collection), they fail to parse and get stripped before the model is passed to the ApiController method. Given the classes below, a valid input should contain only numeric values for "PerferredNutTypes" and "GeographyIDs".
Classes
public class SquirrelController : ApiController
{
[HttpPost]
[Route("api/squirrels/search")]
[SwaggerResponse(HttpStatusCode.OK, Type = typeof(SquirrelsResponse))]
public HttpResponseMessage Squirrels(SquirrelsRequest model)
{
// model already parsed by the time breakpoint reaches here and non-convertable elements already stripped
...
...
...
SquirrelsResponse results = Targeting.SearchForSquirrels(model);
return Request.CreateResponse(HttpStatusCode.OK, results);
}
}
public class SquirrelsRequest
{
public SquirrelsRequest() {}
public List<long> PreferredNutTypes { get; set; } = new List<long>();
public GeographySearch geographySearch { get; set; } = new GeographySearch();
}
public class GeographySearch
{
public GeographySearch() {}
public BooleanOperator Operator { get; set; } = BooleanOperator.OR;
public List<long> GeographyIDs { get; set; } = new List<long>();
}
public enum BooleanOperator
{
AND,
OR
}
Examples:
//"Toronto" sould be an invalid input when converting from JSON string array to c# long collection.
{
"PreferredNutTypes": [34,21],
"GeographySearch": {
"Operator": 1,
"GeographyIDs": ["Toronto"]
},
}
// This is what the model currently looks like in public HttpResponseMessage Squirrels(SquirrelsRequest model)
new SquirrelsRequest()
{
PreferredNutTypes = new List<long>() { 34, 21 },
GeographySearch = new GeographySearch()
{
Operator = 1
GeographyIDs = new List<long>()
}
}
Expectations:
Things I've attempted:
System.Web.Http.Controllers.HttpActionContext actionContext.ModelState.["model.GeographySearch.GeographyIDs[0]"].Errors[0].Exception.Message => "Error converting value "sonali7678687" to type 'System.Int64'. Path 'subjectSearch.writingAbout[0]', line 6, position 36."
System.Web.Http.Controllers.HttpActionContext actionContext.ModelState.["model.GeographySearch.GeographyIDs[0]"].Errors[0].Exception.InnerException.Message => "Input string was not in a correct format."
... surely there must be a better way of validating?
UPDATE 1:
Rephrased question to make explanation and intent more clear.
c# asp.net asp.net-mvc data-annotations asp.net-apicontroller
How can I validate and catch collection type conversion (JSON string array to C# long collection) for my System.Web.Http.ApiController class (before the model is initialized if possible)?
I want to validate and catch any non-numeric elements in the JSON array to be return as a bad request response (maybe somehow with data annotation).
When non-numeric JSON elements are included (to be converted to long collection), they fail to parse and get stripped before the model is passed to the ApiController method. Given the classes below, a valid input should contain only numeric values for "PerferredNutTypes" and "GeographyIDs".
Classes
public class SquirrelController : ApiController
{
[HttpPost]
[Route("api/squirrels/search")]
[SwaggerResponse(HttpStatusCode.OK, Type = typeof(SquirrelsResponse))]
public HttpResponseMessage Squirrels(SquirrelsRequest model)
{
// model already parsed by the time breakpoint reaches here and non-convertable elements already stripped
...
...
...
SquirrelsResponse results = Targeting.SearchForSquirrels(model);
return Request.CreateResponse(HttpStatusCode.OK, results);
}
}
public class SquirrelsRequest
{
public SquirrelsRequest() {}
public List<long> PreferredNutTypes { get; set; } = new List<long>();
public GeographySearch geographySearch { get; set; } = new GeographySearch();
}
public class GeographySearch
{
public GeographySearch() {}
public BooleanOperator Operator { get; set; } = BooleanOperator.OR;
public List<long> GeographyIDs { get; set; } = new List<long>();
}
public enum BooleanOperator
{
AND,
OR
}
Examples:
//"Toronto" sould be an invalid input when converting from JSON string array to c# long collection.
{
"PreferredNutTypes": [34,21],
"GeographySearch": {
"Operator": 1,
"GeographyIDs": ["Toronto"]
},
}
// This is what the model currently looks like in public HttpResponseMessage Squirrels(SquirrelsRequest model)
new SquirrelsRequest()
{
PreferredNutTypes = new List<long>() { 34, 21 },
GeographySearch = new GeographySearch()
{
Operator = 1
GeographyIDs = new List<long>()
}
}
Expectations:
Things I've attempted:
System.Web.Http.Controllers.HttpActionContext actionContext.ModelState.["model.GeographySearch.GeographyIDs[0]"].Errors[0].Exception.Message => "Error converting value "sonali7678687" to type 'System.Int64'. Path 'subjectSearch.writingAbout[0]', line 6, position 36."
System.Web.Http.Controllers.HttpActionContext actionContext.ModelState.["model.GeographySearch.GeographyIDs[0]"].Errors[0].Exception.InnerException.Message => "Input string was not in a correct format."
... surely there must be a better way of validating?
UPDATE 1:
Rephrased question to make explanation and intent more clear.
c# asp.net asp.net-mvc data-annotations asp.net-apicontroller
c# asp.net asp.net-mvc data-annotations asp.net-apicontroller
edited Nov 20 '18 at 14:36
setzuiro
asked Nov 19 '18 at 21:01
setzuirosetzuiro
167212
167212
1
TheModelState
errors are telling you want is invalid (i.e. in the example you gave, its telling you that the first value ofGeographyIDs
is invalid) so its not clear what you are expecting or want to do.
– user3559349
Nov 19 '18 at 22:15
I think you can get the current value fromRequest["GeographySearch.GeographyId"]
, but I would just look atModelState.Where(m => m.Errors.Count > 0)
and return a genericResponse.StatusCode = 404
if the result is not null to keep it simple.
– Kristianne Nerona
Nov 20 '18 at 0:16
add a comment |
1
TheModelState
errors are telling you want is invalid (i.e. in the example you gave, its telling you that the first value ofGeographyIDs
is invalid) so its not clear what you are expecting or want to do.
– user3559349
Nov 19 '18 at 22:15
I think you can get the current value fromRequest["GeographySearch.GeographyId"]
, but I would just look atModelState.Where(m => m.Errors.Count > 0)
and return a genericResponse.StatusCode = 404
if the result is not null to keep it simple.
– Kristianne Nerona
Nov 20 '18 at 0:16
1
1
The
ModelState
errors are telling you want is invalid (i.e. in the example you gave, its telling you that the first value of GeographyIDs
is invalid) so its not clear what you are expecting or want to do.– user3559349
Nov 19 '18 at 22:15
The
ModelState
errors are telling you want is invalid (i.e. in the example you gave, its telling you that the first value of GeographyIDs
is invalid) so its not clear what you are expecting or want to do.– user3559349
Nov 19 '18 at 22:15
I think you can get the current value from
Request["GeographySearch.GeographyId"]
, but I would just look at ModelState.Where(m => m.Errors.Count > 0)
and return a generic Response.StatusCode = 404
if the result is not null to keep it simple.– Kristianne Nerona
Nov 20 '18 at 0:16
I think you can get the current value from
Request["GeographySearch.GeographyId"]
, but I would just look at ModelState.Where(m => m.Errors.Count > 0)
and return a generic Response.StatusCode = 404
if the result is not null to keep it simple.– Kristianne Nerona
Nov 20 '18 at 0:16
add a comment |
2 Answers
2
active
oldest
votes
You can try JSON Schema validator, modify your method to receive JSON body, valid it first then convert it to model.
public class SquirrelController : ApiController
{
[HttpPost]
[Route("api/squirrels/search")]
public SquirrelsResponse Squirrels(PostBody model)
{
var generator = new JSchemaGenerator();
var schema = generator.Generate(typeof(SquirrelsRequest));
var body = JObject.Parse(model.Body);
bool valid = body.IsValid(schema, out IList<string> messages);
if (!valid)
{
// Fail, do something
}
// Success
}
}
public class PostBody
{
public string Body { get; set; }
}
Get more info...
Validating JSON with JSON Schema
Json.NET Schema
you can't validate it like that since messages will be empty if it's invalid
– Marc
Nov 20 '18 at 13:30
@Marc If you just accept request as a string like I said, not model, it would not invalid.
– Died
Nov 21 '18 at 5:45
Sorry I missed that part but then he changes the api. It would be confusing for the customer to see a string instead of a list of longs
– Marc
Nov 21 '18 at 13:07
add a comment |
Why is your type long? Also, are you going to be working with decimals? If not, what you need is int.TryParse(). Wherever you have int.parse (or long.parse() in your case) Replace it with int.TryParse(). TryParse returns a boolean (True or False) that will let you know if the string to be parsed was a number or not.
example:
bool isNumber = int.TryParse("Data I'm Trying to parse but it's a string", variableTheResultWillGetStoredToifSuccessful);
This will come back false, and my super long variable name that you should never use is going to stay empty or rather unchanged. Therefore, you can do
if(isNumber == false){
//skip storing the number
}else{
//keep doing what you're doing;
}
You can also do, more concisely a rewrite of the above:
if(isNumber){
//keep doing what you're doing
}
More or less, that's the summary of it. TryParse will return a true or false based on if the parsing was successful or not without crashing your code, then you can use that information to continue how you seem fit.
If you're going to be working with decimals use double instead of int.
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53382558%2fhow-to-validate-type-of-collections%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
You can try JSON Schema validator, modify your method to receive JSON body, valid it first then convert it to model.
public class SquirrelController : ApiController
{
[HttpPost]
[Route("api/squirrels/search")]
public SquirrelsResponse Squirrels(PostBody model)
{
var generator = new JSchemaGenerator();
var schema = generator.Generate(typeof(SquirrelsRequest));
var body = JObject.Parse(model.Body);
bool valid = body.IsValid(schema, out IList<string> messages);
if (!valid)
{
// Fail, do something
}
// Success
}
}
public class PostBody
{
public string Body { get; set; }
}
Get more info...
Validating JSON with JSON Schema
Json.NET Schema
you can't validate it like that since messages will be empty if it's invalid
– Marc
Nov 20 '18 at 13:30
@Marc If you just accept request as a string like I said, not model, it would not invalid.
– Died
Nov 21 '18 at 5:45
Sorry I missed that part but then he changes the api. It would be confusing for the customer to see a string instead of a list of longs
– Marc
Nov 21 '18 at 13:07
add a comment |
You can try JSON Schema validator, modify your method to receive JSON body, valid it first then convert it to model.
public class SquirrelController : ApiController
{
[HttpPost]
[Route("api/squirrels/search")]
public SquirrelsResponse Squirrels(PostBody model)
{
var generator = new JSchemaGenerator();
var schema = generator.Generate(typeof(SquirrelsRequest));
var body = JObject.Parse(model.Body);
bool valid = body.IsValid(schema, out IList<string> messages);
if (!valid)
{
// Fail, do something
}
// Success
}
}
public class PostBody
{
public string Body { get; set; }
}
Get more info...
Validating JSON with JSON Schema
Json.NET Schema
you can't validate it like that since messages will be empty if it's invalid
– Marc
Nov 20 '18 at 13:30
@Marc If you just accept request as a string like I said, not model, it would not invalid.
– Died
Nov 21 '18 at 5:45
Sorry I missed that part but then he changes the api. It would be confusing for the customer to see a string instead of a list of longs
– Marc
Nov 21 '18 at 13:07
add a comment |
You can try JSON Schema validator, modify your method to receive JSON body, valid it first then convert it to model.
public class SquirrelController : ApiController
{
[HttpPost]
[Route("api/squirrels/search")]
public SquirrelsResponse Squirrels(PostBody model)
{
var generator = new JSchemaGenerator();
var schema = generator.Generate(typeof(SquirrelsRequest));
var body = JObject.Parse(model.Body);
bool valid = body.IsValid(schema, out IList<string> messages);
if (!valid)
{
// Fail, do something
}
// Success
}
}
public class PostBody
{
public string Body { get; set; }
}
Get more info...
Validating JSON with JSON Schema
Json.NET Schema
You can try JSON Schema validator, modify your method to receive JSON body, valid it first then convert it to model.
public class SquirrelController : ApiController
{
[HttpPost]
[Route("api/squirrels/search")]
public SquirrelsResponse Squirrels(PostBody model)
{
var generator = new JSchemaGenerator();
var schema = generator.Generate(typeof(SquirrelsRequest));
var body = JObject.Parse(model.Body);
bool valid = body.IsValid(schema, out IList<string> messages);
if (!valid)
{
// Fail, do something
}
// Success
}
}
public class PostBody
{
public string Body { get; set; }
}
Get more info...
Validating JSON with JSON Schema
Json.NET Schema
edited Dec 10 '18 at 2:05
MonLiH
8110
8110
answered Nov 20 '18 at 8:30
DiedDied
12
12
you can't validate it like that since messages will be empty if it's invalid
– Marc
Nov 20 '18 at 13:30
@Marc If you just accept request as a string like I said, not model, it would not invalid.
– Died
Nov 21 '18 at 5:45
Sorry I missed that part but then he changes the api. It would be confusing for the customer to see a string instead of a list of longs
– Marc
Nov 21 '18 at 13:07
add a comment |
you can't validate it like that since messages will be empty if it's invalid
– Marc
Nov 20 '18 at 13:30
@Marc If you just accept request as a string like I said, not model, it would not invalid.
– Died
Nov 21 '18 at 5:45
Sorry I missed that part but then he changes the api. It would be confusing for the customer to see a string instead of a list of longs
– Marc
Nov 21 '18 at 13:07
you can't validate it like that since messages will be empty if it's invalid
– Marc
Nov 20 '18 at 13:30
you can't validate it like that since messages will be empty if it's invalid
– Marc
Nov 20 '18 at 13:30
@Marc If you just accept request as a string like I said, not model, it would not invalid.
– Died
Nov 21 '18 at 5:45
@Marc If you just accept request as a string like I said, not model, it would not invalid.
– Died
Nov 21 '18 at 5:45
Sorry I missed that part but then he changes the api. It would be confusing for the customer to see a string instead of a list of longs
– Marc
Nov 21 '18 at 13:07
Sorry I missed that part but then he changes the api. It would be confusing for the customer to see a string instead of a list of longs
– Marc
Nov 21 '18 at 13:07
add a comment |
Why is your type long? Also, are you going to be working with decimals? If not, what you need is int.TryParse(). Wherever you have int.parse (or long.parse() in your case) Replace it with int.TryParse(). TryParse returns a boolean (True or False) that will let you know if the string to be parsed was a number or not.
example:
bool isNumber = int.TryParse("Data I'm Trying to parse but it's a string", variableTheResultWillGetStoredToifSuccessful);
This will come back false, and my super long variable name that you should never use is going to stay empty or rather unchanged. Therefore, you can do
if(isNumber == false){
//skip storing the number
}else{
//keep doing what you're doing;
}
You can also do, more concisely a rewrite of the above:
if(isNumber){
//keep doing what you're doing
}
More or less, that's the summary of it. TryParse will return a true or false based on if the parsing was successful or not without crashing your code, then you can use that information to continue how you seem fit.
If you're going to be working with decimals use double instead of int.
add a comment |
Why is your type long? Also, are you going to be working with decimals? If not, what you need is int.TryParse(). Wherever you have int.parse (or long.parse() in your case) Replace it with int.TryParse(). TryParse returns a boolean (True or False) that will let you know if the string to be parsed was a number or not.
example:
bool isNumber = int.TryParse("Data I'm Trying to parse but it's a string", variableTheResultWillGetStoredToifSuccessful);
This will come back false, and my super long variable name that you should never use is going to stay empty or rather unchanged. Therefore, you can do
if(isNumber == false){
//skip storing the number
}else{
//keep doing what you're doing;
}
You can also do, more concisely a rewrite of the above:
if(isNumber){
//keep doing what you're doing
}
More or less, that's the summary of it. TryParse will return a true or false based on if the parsing was successful or not without crashing your code, then you can use that information to continue how you seem fit.
If you're going to be working with decimals use double instead of int.
add a comment |
Why is your type long? Also, are you going to be working with decimals? If not, what you need is int.TryParse(). Wherever you have int.parse (or long.parse() in your case) Replace it with int.TryParse(). TryParse returns a boolean (True or False) that will let you know if the string to be parsed was a number or not.
example:
bool isNumber = int.TryParse("Data I'm Trying to parse but it's a string", variableTheResultWillGetStoredToifSuccessful);
This will come back false, and my super long variable name that you should never use is going to stay empty or rather unchanged. Therefore, you can do
if(isNumber == false){
//skip storing the number
}else{
//keep doing what you're doing;
}
You can also do, more concisely a rewrite of the above:
if(isNumber){
//keep doing what you're doing
}
More or less, that's the summary of it. TryParse will return a true or false based on if the parsing was successful or not without crashing your code, then you can use that information to continue how you seem fit.
If you're going to be working with decimals use double instead of int.
Why is your type long? Also, are you going to be working with decimals? If not, what you need is int.TryParse(). Wherever you have int.parse (or long.parse() in your case) Replace it with int.TryParse(). TryParse returns a boolean (True or False) that will let you know if the string to be parsed was a number or not.
example:
bool isNumber = int.TryParse("Data I'm Trying to parse but it's a string", variableTheResultWillGetStoredToifSuccessful);
This will come back false, and my super long variable name that you should never use is going to stay empty or rather unchanged. Therefore, you can do
if(isNumber == false){
//skip storing the number
}else{
//keep doing what you're doing;
}
You can also do, more concisely a rewrite of the above:
if(isNumber){
//keep doing what you're doing
}
More or less, that's the summary of it. TryParse will return a true or false based on if the parsing was successful or not without crashing your code, then you can use that information to continue how you seem fit.
If you're going to be working with decimals use double instead of int.
answered Nov 19 '18 at 21:42
The.NetDeveloperThe.NetDeveloper
13
13
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53382558%2fhow-to-validate-type-of-collections%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
1
The
ModelState
errors are telling you want is invalid (i.e. in the example you gave, its telling you that the first value ofGeographyIDs
is invalid) so its not clear what you are expecting or want to do.– user3559349
Nov 19 '18 at 22:15
I think you can get the current value from
Request["GeographySearch.GeographyId"]
, but I would just look atModelState.Where(m => m.Errors.Count > 0)
and return a genericResponse.StatusCode = 404
if the result is not null to keep it simple.– Kristianne Nerona
Nov 20 '18 at 0:16