Search code examples
asp.netangularjsasp.net-mvcasp.net-mvc-4asp.net-mvc-5

How to use Angular JS brackets inside ASP.NET ViewBag to display the ViewBag.title


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.


Solution

  • 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();  
    }