Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to display value by selecting from model in the controller ASP MVC

I want to display a name in the razor page by select it from a model and pass it through Viewbag in the controller.

Controller

public IActionResult sheet()
    {
        var tp1 = _db.Topic.Where(t => t.sheet_id == 1).ToList();
        var tp1name = tp1.Select(t => t.topic1name);
        ViewBag.tp1name = tp1name;
        return View();
    }

Model

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

public class Topic
{
    [Key]
    public int topic_id { get; set; }
    [Required]
    public int sheet_id { get; set; }
    [Required]
    public string topic1name { get; set; }
    [Required]
    public string topic2name { get; set; }
}
public class Transaction
{
    [Key]
    public int id { get; set; }
    [Required]
    public int sheet_id { get; set; }
    [Required]
    public string topic1score { get; set; }
}

View page

@model transaction
<table class="table">
 <tr>
    <td rowspan="2">1</td>
    <td rowspan="2">@ViewBag.tp1name</td>
    <td rowspan="2">30</td>
    <td>Below average</td>
    <td>Average</td>
    <td>Above average</td>
  </tr>

It returns
System.Linq.Enumerable+SelectListIterator`2[UserLoginApp.Models.Topic,System.String] in the view page instead of topic1name

>Solution :

tp1 is a list of topics.
so when you do a select it creates a new Enumerable en for each item in tp1 it selects the value of topic1name.

Thus creating an Enumerable+SelectListIterator

I think you want the value of one item:

    var tp1 = _db.Topic.FirstOrDefault(t => t.sheet_id == 1)
    if(tp1 != null)
         ViewBag.tp1name = tp1.topic1name;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading