How to access DbContext in viewmodel with AspNetCore 2.1?

asp.net-core-2.1 dbcontext entity-framework-core viewmodel

Question

Using DropDown input fields is very common when you want to display a description while saving an ID in your database. If I consider my Person model, I have PersonViewModel which has a SelectList used to display a list of possible Job Descriptions

    public SelectList SelectJobDescription
    {
        get
        {
            MyDbContext _context = new MyDbContext();
            var result = new SelectList(_context.Keywords
                                    .Where(k => k.Name == ".JobDescription")
                                    .OrderBy(r => r.Valuename), "Valuecode", "Valuename");
            _context.Dispose();
            return result;
        }
    }

and I use this SelectList in my create/edit views like this:

        <div class="form-group row">
            <label asp-for="JobDescription" class="col-sm-4 col-form-label"></label>
            <div class="col-sm-8">
                <select asp-for="JobDescription" asp-items="@Model.SelectJobDescription" class="form-control">
                    <option>Select a Job Description</option>
                </select>
        </div>

Is it correct to use _context this way in the ViewModel or there is some other way to do the same thing better (maybe DI?)

1
0
9/30/2018 5:19:28 AM

Accepted Answer

Set the property after instatiating the view model (or during initialization), for example:

var vm = new YourViewModel()
{
    SelectJobDescription = new SelectList( _context... ),
};

return View( vm );
0
9/30/2018 5:26:09 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow