I have two database table in one table district code is stored and district code is form another table, i want to fetch the value from database table and display in View
if dept = 1 then it will be like '3'
if dept = 2 then it will be like '4'
but in text.

Vishal JoshiRank #377 · 6.7K reputationPosted Dec 15, 2023, 6:40 AM EST
Hello
As per the secnario you need to write query on district master table. As you have district Id and based on that you can get district name from the master table and you can bind the district name along with district id in View Model.
once view model bind is done you can use the view model in aspx or cshtml page.
Please check the below sample query to get district name from district master table.
viewmodel.districtName = db.districtMaster.where(filter => filter.distCode == distCode) .select(s => s.districtName).FirstOrDefault();View model (i.e. cshtml page)
Thanks
Vishal Joshi
Jayraj ChhayaRank #304 · 8.2K reputationPosted Dec 15, 2023, 6:23 AM EST
To fetch the district code from the database and display it in a view, you can follow these steps:
Retrieve the district code from the database based on the "dept" value using a query or an ORM (Object-Relational Mapping) framework like Entity Framework.
In your controller or view model, create a property to store the fetched district code.
public string DistrictCode { get; set; }public IActionResult DisplayDistrictCode(int dept) { // Fetch the district code from the database based on the "dept" value // Assuming you have a DbContext named "dbContext" and a DbSet named "Districts" var district = dbContext.Districts.FirstOrDefault(d => d.Dept == dept); // Assign the district code to the property DistrictCode = district?.Code; return View(); }By following these steps, you will be able to fetch the district code from the database and display it in the desired text format in your view based on the value of the "dept" field.
Anandu G NathRank #681 · 3.5K reputationPosted Dec 21, 2023, 12:58 AM EST
Hai
You can check my below code snippet that illustrates this concept in an ASP.NET MVC Controller:
public class DistrictController : Controller { private readonly YourDbContext dbContext; // Replace with your DbContext public DistrictController() { // Initialize your DbContext dbContext = new YourDbContext(); } public ActionResult GetDistrictCode(int dept) { string districtCode = string.Empty; // Perform a conditional query based on 'dept' value if (dept == 1) { // Fetch district code from the database for dept = 1 districtCode = dbContext.YourTable1.FirstOrDefault()?.DistrictCode; } else if (dept == 2) { // Fetch district code from the database for dept = 2 districtCode = dbContext.YourTable2.FirstOrDefault()?.DistrictCode; } // Pass the districtCode value to the View return View((object)districtCode); // Pass the value to the View } }