Question How to return json result true when exist and false when not exist

ahmedaziz

Well-known member
Joined
Feb 22, 2023
Messages
55
Programming Experience
1-3
I working on mvc asp.net csharp i need to make function return json result when branch code exist then return true and if not exist return false so can you help me do this function return json result true or false

how to return json result true or false:
public JsonResult CheckExist(string BranchCode)
{
 string branches = _db.Branch.Single(x => x.iBranchCode == BranchCode).iBranchCode.ToString();
// so what i write here to return true or false
}
 
What's wrong with setting the Data member of a new instance of a JsonResult to true or false depending whether you want to return true or false?


Not directly related to your question:

It's not clear to me though, why you are using Single() to get an object with a matching branch code. And even more mysterious is that iBranchCode already seems to be a string based on your comparison of [iocde]x.iBranchCode == BranchCode[/icode], yet later you try to convert the string to a string again: iBranchCode.ToString(). What are you going to do with that string? Check to see if it's not empty? What happens if there is no object with a matching branch code? Will you use an exception handler? If so, recall that it is poor programming practice to use exceptions for flow control.

To me it would make more sense to simply use Any() instead of Single().
 
Perhaps like:


C#:
public JsonResult CheckExist(string branchCode) =>
    new JsonResult() { Data =   _db.Branch.Any(x => x.iBranchCode == branchCode);
 

Latest posts

Back
Top Bottom