I am using ChartJS to draw a chart. Only separated values can be processed on the accepted values lables and data. But in my case, the text is monolithic. In general, I cannot format the text in any way when passing List to View.
View
<script>
function chart1() {
var ctx = document.getElementById('myChart');
window.myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: [@foreach (var m in Model) { @m.NameArea}],
datasets: [{
label: 'Районы',
data: [@foreach (var m in Model) { @m.AreaParameter}],
backgroundColor: [
'rgba(255, 99, 132, 0.2)'
],
borderColor: [
'rgba(255, 99, 132, 1)'
],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
};</script>
Controller
public ActionResult Index()
{
string connString = "Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\database.mdf;Integrated Security=True";
using (SqlConnection conn = new SqlConnection(connString))
{
List<Area> currentArea = new List<Area>();
using (var cmd = new SqlCommand("SELECT NameArea, AreaParameter FROM FileTable", conn))
{
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
List<Area> dictList = new List<Area>();
while (reader.Read())
{
currentArea.Add(new Area()
{
//Id = Int32.Parse(reader["id"].ToString()),
NameArea = reader["NameArea"].ToString(),
AreaParameter = Int32.Parse(reader["AreaParameter"].ToString())
});
}
}
conn.Close();
}
conn.Open();
SqlCommand comDelete = new SqlCommand("DELETE FROM FileTable", conn);
comDelete.ExecuteNonQuery();
conn.Close();
return View(currentArea);
}
}
As a result, the script gets the list
labels: [OneTwoThreeFour]
I would like to see
labels: ['One', 'Two', 'Three', 'Four']
I really need help.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
Try formatting your output. Something like below should work.
labels: @String.Join(",", Model.Select(x => $"'{x.NameArea}'"))
So basically what this is doing is instead of a foreach we are selecting just the name area from all of the models in your list. That Select is also adding single quotes around your NameArea using String Interpolation. From there we are doing a join to comma delimit the list.
Hopefully this works for you.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0