简体   繁体   中英

ASP.NET MVC - How to display data in Razor view returned from Webapi controller

I am invoking a Web API controller on page load of my form and getting data, this is from my JS file and data is fetched correctly as expected.

  var empDetails = // code to invoke my api controller //
  empDetails.$promise.then(function (empInfo) {
      $scope.employeeForm.EmpDetails = empInfo.EmployeeDetails;
  }); 

$scope.employeeForm.EmpDetails has the details correctly.

I need to display the data in my razor view engine which is where I am having an issue, I am new to this kind of development.

ViewBag, strongly typed model doesn't work here as I am returning data from a Web API controller and mine is not a strongly typed razor view.

EmpDetails has info like EmpID, EmpFirstName, EmpLastName, EmpLocationj

Dear there are two ways

  1. If you are bound to use Razor, then you should consume your api in mvc controller, get data from your api and return it in a model to your Razor view, then you will have strongly typed model to use in your Razor view

  2. If you are not bound then its pretty simple, if you are getting data in javascript code. just use it to populate your view using JavaScript code.

  3. If you are using angular 1.x, then here is a angularjs 1.x form example

<!DOCTYPE html>
<html lang="en">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="formCtrl">
  <form novalidate>
    First Name:<br>
    <input type="text" ng-model="user.firstName"><br>
    Last Name:<br>
    <input type="text" ng-model="user.lastName">
    <br><br>
    <button ng-click="reset()">RESET</button>
  </form>
  <p>form = {{user}}</p>
  <p>master = {{master}}</p>
</div>

<script>
var app = angular.module('myApp', []);
app.controller('formCtrl', function($scope) {
    $scope.master = {firstName:"John", lastName:"Doe"};
    $scope.reset = function() {
        $scope.user = angular.copy($scope.master);
    };
    $scope.reset();
});
</script>
</body>
</html>

Developer as per you are telling in comment that to bind data via html for that this solution you can try this.

First initialize model in .cshtml in the header part of the .cshtml after that use @model and give their field name by adding . (dot) sign and bind data to your html control

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM