None
None

Reputation: 5670

Get data for display purpose only in MVC 5, EF 6

My model class is like this

public class Appointment
{
    public int AppointmentID { get; set; }
    public string Name { get; set; }
    public int ProcedureID { get; set; }
    public virtual Department Department { get; set; }
    public virtual Procedure Procedure { get; set; }
}

And inside my controller

public ActionResult Create()
{
    ViewBag.ProcedureID = new SelectList(db.Procedures, "ProcedureID", "ViCode");
    return View();
}

In view

@Html.DropDownList("ProcedureID", null, new { @class = "form-control" })

This way I could show all procedures, But how could I show all Departments, I don't want to add a field called DepartmentID inside the model because it will act as a foreign key in the table then, which I do not want. My usage with Departments is for show only purpose. How could I achieve this?

Upvotes: 0

Views: 225

Answers (2)

Stilgar
Stilgar

Reputation: 23551

Use a ViewModel. The View Model is a class you make specifically to send data from the controller to the View. It is not the entity you use in Entity framework. It can contain entities, lists of entities, SelectList objects and any combinations of things you need. It also has the benefit of being statically typed (unlike the ViewBag)

public class CreateViewModel
{
    public SelectList Producers {get; set;}
    public List<Department> Departments {get; set;}
    public int SelectedProducerID {get; set;}
}

In the Controller

var model = new CreateViewModel
            {
               Producers = new SelectList(db.Procedures, "ProcedureID", "ViCode");
               Departments = db.Departments.ToList()
            }

return View(model);

In the View

@Html.DropDownListFor(model => model.SelectedProducerID, Model.Producers, ...)

I don't know how you want to display the departments but you can just loop through them and display them in the html. I have not tested the code.

Upvotes: 2

Pranay Rana
Pranay Rana

Reputation: 176896

try like this , pure html + Razor suntax

<select name="departments">
  @for (var i = 0; i < model.Departments ; i++){

    <option>@(model.Departments[i])</option>
  }
</select>

Upvotes: 2

Related Questions