How to use MVC viewBag concept in express js?

476 views Asked by At

I am using express js 4.1 along with handlebars template 4.0. When rendering a page I am sending collection of objects from express route.get('/') to handlebar(.hbs) view file. Is there any possibility to the send object like viewbag (similar to MVC) and should access those objects using @viewbag in hbs file? Below code is used to render the hbs file along with collection of 2 objects

var gridData =  [
          { Name: 'xxxx', City: 'dddd' },
          { Name: 'yyyy', City: 'rrrr' },
          { Name: 'zzzz', City: 'ssss' }
    ]
resultSet["gridData"] = gridData;
resultSet["newdata"] = [1,2,3];
res.render('user-list',  {viewBag: resultSet});

Here I need to use the viewBag as @viewBag.gridData or @viewBag.newdata in hbs to bind these array values. Also, please suggest how to use @HTML helpers and @section ControlsSection{} in hbs file since the express js follows MVC structure.

1

There are 1 answers

0
Dhya S On BEST ANSWER

Instead of res.render('user-list', {viewBag: gridData}); I have replaced

res.locals.gridData = JSON.stringify(gridData); // To make it global and accessible in hbs view file
res.locals.newdata = newdata; 
res.render('user-list');

When rendering 'user-list' page, dataSource: {{{gridData}}} will bind the respective datasource in for the grid and this datasource is of json type. It works finally!!!