0

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.

Dhya S
  • 143
  • 2
  • 14
  • Change this line to `res.render('user-list', {viewBag: resultSet})` – Aruna Jan 04 '17 at 05:24
  • Yup.. that is fine.. My actual question is how to use HTML helpers and @viewBag in hanblebars. – Dhya S Jan 04 '17 at 05:27
  • You can't use DotNet libraries in NodeJS. You should find the alternative npm packages or better write your own. – Aruna Jan 04 '17 at 05:30
  • Also, instead of `@`, you should follow `handlebars` syntax when dealing with the json data such as `{{viewBag.gridData}}` something like this. – Aruna Jan 04 '17 at 05:32
  • I should bind this viewBag.gridData as datasource for a grid. I will bind this datasource in inside the tag in the hbs view file. Since i am using it inside the script tag, i am unable to use like this {{viewBag.gridData}} – Dhya S Jan 04 '17 at 05:39
  • In case of array, you should use a syntax like this, `{{#each viewBag.gridData}}
  • {{this.Name}}
  • {{/each}}`. You can check this link, http://www.tutorialsavvy.com/2013/10/using-handlebar-template-for-json-response.html/ – Aruna Jan 04 '17 at 05:42
  • I can able to deal with displaying arrays in hbs file. But I need to bind these arrays to "Datasource" property of a grid when rendering the page. Hence I have go for MVC structure and asked how to use it in express js. – Dhya S Jan 04 '17 at 05:53
  • You should go with jQuery data table library then instead of hibernate. Each library and framework are different and you can't use everything in express/ handlebars/other libraries as same as MVC – Aruna Jan 04 '17 at 06:11