Question

I use entity with db first in mvc4(razor)

Requirement:I have sp returning id and display name, I need to display the names in @html.listboxfor i used interface to get the details from stored procedure.When I get the result in the controller from stored procedure,I got struck in saving the result to listbox, I couldnt figure out how to store it in listbox. I got struck in the controller code.Please help.

Code:

public class projService :Iproj
{
    project dbContext;

    public projService()
    {
        dbContext = new projectEntities();
    }

    public List<GetResourceOrderDisplay_Result> Getresorderdisplay()
    {
        List<GetResourceOrderDisplay_Result> oGetresorderdisplay = new List<GetResourceOrderDisplay_Result>();
        oGetresorderdisplay = dbContext.GetResourceOrderDisplay().ToList();
        return oGetresorderdisplay.ToList();
    }
}

controller:

public ActionResult testview()
{
    List<GetResourceOrderDisplay_Result> listboxdata = new List<GetResourceOrderDisplay_Result>();
    listboxdata = _Scheduler.Getresorderdisplay();
    ListboxViewModel objListboxViewModel = new ListboxViewModel();

    //struck with the follwing line.
    objListboxViewModel.resourcename=listboxdata ????

    return View(objListboxViewModel); 
}

view:

@model project.ViewModels.ListboxViewModel
@Html.ListBoxFor( m=> m.resourcename,Model.resourcename, new { @class = "resList",style="height: 462px;"})

model:

public class ListboxViewModel
{
    public string resourceid{get; set; }
    //listbox Values
    public List<SelectListItem> resourcename{get; set;}
}

Edit:GetResourceOrderDisplay_Result

using System;
using System.Collections.Generic;

namespace proj.Data
{
    public partial class GetResourceOrderDisplay_Result
    {
        public int ID { get; set; }
        public string DisplayName { get; set; }
        }
   }

Edit2: this is the error I'm getting after the update: enter image description here

**Edit 3:**

enter image description here

Was it helpful?

Solution

Basically what you need to do is transform the list data you have retrieved from the database into a List<SelectListItem> so it can be displayed. The Linq Select method makes this pretty easy:

objListboxViewModel.resourcename =
    listboxdata.Select(x => new SelectListItem() { Text = x.DisplayName,
                                                   Value = x.ID.ToString() })
               .ToList();

So what you set the Text and Value properties to will depend on what the definition of GetResourceOrderDisplay_Result looks like and what properties it has. In the Select method the x represents a single element of the listboxdata list and is of type GetResourceOrderDisplay_Result, so you can access it's properties like x.Property. The Select method constructed in this way will return a new list of SelectListItem.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top