Hi,
I am trying to bind a model to an select element in Blazor /.net 5. I already have one that reads a json file and that works fine but this one I am trying to get the data from a database. The problem comes when I try and get the DataTable into my Model. So I created a List
Can anyone tell me how to do this correctly? Help Appreciated..Thanks...
private StatesModel USStates { get; set; }
private Task GetStatesModel()
{
DataTable dt = new DataTable();
SQL.GetSQLData exe = new SQL.GetSQLData();
dt = (DataTable)exe.GetValues("storedProcName", "ConnStringName");
List
USStates = StateList; --- Cannot Convert list
//foreach (var item in StateList)
//{
// USStates.States.Add(item); -- Null Reference exception.
//}
return Task.CompletedTask;
}
and my Model......
public class StatesModel
{
public List
}
public class StateModel
{
public string StateName { get; set; }
public string StateAbbreviation { get; set; }
}
---------------------------------------------------------------------------------------------------
FYI I also tried this USStates.States = StateList; - and I get a null reference exception at runtime on this line.
Jignesh KumarRank #91 · 22.9K reputationPosted Dec 17, 2021, 10:00 PM EST
Hi,
You are trying to map two different model. Please try this one,
private Task GetStatesModel() { DataTable dt = new DataTable(); SQL.GetSQLData exe = new SQL.GetSQLData(); dt = (DataTable)exe.GetValues("storedProcName", "ConnStringName"); List StateList = Data.Conversion.ConvertDataTabletoModel.ConvertToList(dt); var USStates = new List(); //If you need only US records then you need to filter your List here StateList = StateList.Where(x => x.StateName == "United States").ToList() USStates.AddRange(StateList); return Task.CompletedTask; } public class StatesModel { public List States { get; set; } = new List(); } public class StateModel { public string StateName { get; set; } public string StateAbbreviation { get; set; } }David Smith29 reputationPosted Dec 20, 2021, 8:55 AM EST
David Smith29 reputationPosted Dec 20, 2021, 10:06 AM EST
Jignesh KumarRank #91 · 22.9K reputationPosted Dec 21, 2021, 3:31 AM EST
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questionsTop experts