0

What I am trying to achieve is as follows:

  1. I am using AngularJS and ASP.NET MVC to build my project.
  2. I have made a product page where I need the title to be displayed according to the product name.
  3. In this I have used brackets {{ }} to display the name of the product. Similarly I am trying to use the brackets or ng-model or ng-init or ng-value to be used to display the title usng viewbag.title.

Example:

I am getting the data from .js file

$scope.getdata = function(){
   $http.get(urlApi).then(function(response){
      $scope.AllRecords = response.data;
   });
}

Now on ASP.NET MVC I am trying to achieve the record value inside ViewBag.title like below:

@{
  ViewBag.title = {{ AllRecords.Name }};
}

I am unable to get the record in ViewBag.title. Please suggest the idea of achieving this if this way is not possible.

Thanks in Advance.

1 Answers1

0

Following code will execute in the sever level at first

@{
  ViewBag.title = {{ AllRecords.Name }};
}

then following will execute at browser level

$scope.getdata = function(){
   $http.get(urlApi).then(function(response){
      $scope.AllRecords = response.data;
   });
} 

when it comes to execute js at browser, you don't have ViewBag.title in the browser level. To achieve this. it is good to set ViewBag.title at server level. ex :

public ActionResult Index()   
{  
   ViewBag.title  = GetAllRecordes();
   return View();  
}
  • I have tried using @{ ViewBag.title = {{ AllRecords.Name }}; } but it is not working. Additionally I am passing the Id from ActionResult method, so that is working fine to fetch the data using Angularjs but it is something which is not helping me in getting the data inserted again to title using {{ }} brackets – Tushant Rajpal Jul 31 '20 at 16:43
  • @Tushant Rajpal, @{ ViewBag.title = {{ AllRecords.Name }}; } this is also wrong because as per your code AllRecords is being pulled at client side (in browser) where ViewBag.title is no longer exist at client side. As per the ASP.NET MVC life cycle your razor view is executed at server and send html to your browser. After html page loads to the browser then angularJs function start to fire. that time you don't have sever variable. – Chaminda Jayanath Udawatte Aug 01 '20 at 04:40
  • Okay I see. so what will be the other alternatives in this situation??? As I need to use the Name of the product in the title but unable to use it with ASP.NET MVC and AngularJS. – Tushant Rajpal Aug 01 '20 at 14:55
  • There many alternatives. please refer this https://stackoverflow.com/questions/12506329/how-to-dynamically-change-header-based-on-angularjs-partial-view – Chaminda Jayanath Udawatte Aug 02 '20 at 10:33
  • Yes you are correct!. The viewbage.title can only be achieved through controller not via Angular JS file. I have tired all senarios but it has not worked any which is linked with view and js file. Thanks – Tushant Rajpal Aug 27 '20 at 06:37