Click here to Skip to main content
15,846,091 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
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

What I have tried:

httpget
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
}
Posted
Updated 5-Jun-23 4:38am

Quote:
... when branch code exist then return true and if not exist return false ...
C#
string branches = _db.Branch.Single(x => x.iBranchCode == BranchCode).iBranchCode.ToString();
If the branch doesn't exist, the Single method will throw an InvalidOperationException:
Enumerable.Single Method (System.Linq) | Microsoft Learn[^]

Instead, use Any to test whether there is a branch that meets your condition:
Enumerable.Any Method (System.Linq) | Microsoft Learn[^]
C#
public JsonResult CheckExist(string BranchCode)
{
    bool branchExists = _db.Branch.Any(x => x.iBranchCode == BranchCode);
    return Json(branchExists);
}
 
Share this answer
 
The JSON for true is a string containing the word "true".
I think you can guess what the JSON for false is.

If necessary, you can wrap this in a class: "value:true" that gives you a bool property:
public class Root
    {
    public bool value { get; set; }
    }
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900