View.Bag returning null

Asked

Viewed 74 times

-1

I am creating an APS.NET CORE form with C# and Sqlserver sending email and one of the fields is a dropdownlist that lists data from a table.

List<Templates> templates = new List<Templates>();
templates = _context.Templates.ToList();
ViewBag.languageTemplates = templates;
return View();

The "templates" list is populated with table data, but Viewbag returns NULL in the View. Could someone give me a hand, I’m learning this technology now.

2 answers

0

I don’t know what the context object is but I think it’s a database context, right?

If it is you need to do a query on top of that object to return to your list.

var templates = (from template in _context.Templates
                 select template).ToList()

The . Tolist() at the end will materialize your query and return a list instead of a Iqueryable. However I must say that putting this list in Viewbag is not the best aproach, try to put the list in your Viewmodel and return to Viewmodel inside your Return this.View();

It is also not recommended to make database queries inside your controller, look for the Unitofwork and Repository Pattern Pattern.

0

I found the problem, it was nothing programming and not structure, it was passing a field in the construction of the Dropdownlist with the name of the wrong field. The NULL he was returning was because he didn’t have this "attribute" in the object. Thanks @crawletas.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.