RememberME
RememberME

Reputation: 2092

Display list of values in MVC Detail View

I am new to web apps, MVC, and LinqToSql. I created an MVC web app using the NerdDinner tutorial as a guide. I'm now adding many-to-many relationships to it. And am just running into walls at every step. I have a multiselect list in the Edit and Create views. For the Detail and List views I would like to list the selected values.

I have 3 tables: Company, Subcontract, and a link table CompanyToSubcontract. I have code which gets the guid of my selected companies from the CompanyToSubcontract table which is used elsewhere in my code. I do not know how to display it.

Should I write another function to get the Company names from the Company table? Do I pass the list of names to the SubcontractDetail view and then somehow loop through it there?

Same questions with the SubcontractIndex view. The Index view is in table format, I'd like to have a "Company" column which has a comma separated list of the companies for each subcontract row.

[Authorize]
        public ActionResult Details(string id)
        {
           subcontract subcontract = subcontractRepository.GetSubcontract(id);

           IEnumerable<Guid> cmpny = subcontractRepository.GetSubcontractCompanies(subcontract.subcontract_id);

           if (subcontract == null)
               return View("NotFound");
           else
           {
               return View("Details", subcontract);
           }
        }

[Authorize]
    public ActionResult Index()
    {
        var subcontracts = subcontractRepository.FindAllSubcontracts().ToList();
        return View("Index", subcontracts);
    }

Upvotes: 3

Views: 6817

Answers (1)

Branislav Abadjimarinov
Branislav Abadjimarinov

Reputation: 5131

You have several options:
1) You can create new class that contains subcontract & IEnumerable and pass an object of the new class to the view. This is common practice in ASP.NET MVC .

public class MyCustomModelView
{
    public IEnumerable<Guid> Company{ get; set; }
    public subcontract Subcontract { get; set; }
}

And in the controller:

return View("Details", new MyCustomModelView(){
    Company = cmpny, 
    Subcontract = subcontract });

And add this new type should be the type of your view.

enter code here

2) Also you can add the IEnumerable to the ViewData collection like this:

ViewData["Company"] = cmpny;

And then access it with the indexer in the view

<% foreach(Guid id in (ViewData["Company"] as IEnumerable<Guid>)) {  %>
...Display names...
<% } %>

I personally will recomand you the firs because you don't need to cast and it is cleaner

Upvotes: 3

Related Questions