Domanda

In my MVC application I am trying to retrieve data using a stored procedure, then display it in a dropdown.

Here is My controller action

public ActionResult Register(string id )
{ 
    RegistrationModel Student = new RegistrationModel();

        using (var db = new StudentEntities())
        {
            var SportResultList = GetListOfSport();
            var SportSelectList = new SelectList(SportResultList);
            ViewBag.SportList = SportSelectList;

    return View(Student);
}

Here is the Method to get the list using the stored procedure

        public static List<GetSportsResult> GetListOfSport()
                {
       using (var db = new StudentEntities())
          {
ObjectResult<GetSportsResult> SportResults = db.GetSportsByStudentIdAndSeason(11111, 1);
List<GetSportsResult> results = SportResults.ToList();

           return results;
          }

        }

The stored procedure returns a complex type called GetSportsResults but I don't now how to access its fields.

Currently this code will display the GetSportsResults 20 times which is the right amount of records I should be getting

È stato utile?

Soluzione

In the constructor for SelectList you can specify which fields are to be used for the text and for the value. This is done by passing string values to the constructor.

For example, if your GetSportsResult object has a .ID property as its identifier and a .Name property as its display value, then your code would look like this:

var SportResultList = GetListOfSport();
var SportSelectList = new SelectList(SportResultList, "ID", "Name");
ViewBag.SportList = SportSelectList;

This would indicate to the SelectList object that GetSportsResult.ID should be the value for each item in the list, and GetSportsResult.Name should be the displayed text for each item in the list.

Without specifying these fields, currently the object tries to make a "best guess" of what to display. It's probably doing this by calling .ToString() on each object by default. And the default behavior of .ToString() on a non-primative type is to display the name of the type itself, which is why you're seeing the string "GetSportsResult" for each item.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top