2017年11月5日 星期日

[ASP.NET] Web API in Webform project

 ASP.NET    Webform    WebApi      Ajax 


Introduction


This example will shows how to use Web API in a ASP.NET Webform project template.


Environment


Visual Studio 2017 community



Implement


Assume that we have an exist ASP.NET Webform project, if not, create a new one.




OR



Install Web API

Install Web API into the Webform project.



Set routing rule

Open \App_Start\WebApiConfig.cs and update the routing pattern like this

public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }


Create API Controller

Now we can create a controller which inherits ApiController.

On the \Controller, right click to Add a new Controller.





For example, I create an action like following,

public class ReportController : ApiController
{
        [HttpGet]
        [Route("api/Report/Reports")]
        public IEnumerable<Report> GetReports()
        {
            string jsonStr = @"
[
    { 'id' : '1', 'title': '會計報表01'},
                 { 'id' : '2', 'title': '會計報表02'},
                 { 'id' : '3', 'title': '財務報表01'},
                 { 'id' : '4', 'title': '財務報表02'},
                 { 'id' : '5', 'title': '財務報表03'}
              ]";

            var jsonInstance = JsonConvert.DeserializeObject<List<Report>>(jsonStr);
            return jsonInstance.AsEnumerable();
        }
}


Test in Postman like a charm.





Ajax in .aspx

Here is an Ajax sample with Vue.js.


Html (*.aspx)

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.3/vue.min.js"></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>

    <div id="app">
         <select v-model="selectedReport" class="form-control">
            <option v-for="rt in reports" :value="rt">{{ rt.title }}</option>
        </select>

        <div v-if="selectedReport!==null" class="alert alert-warning" role="alert">
            You select {{ selectedReport.title }}
        </div>

    </div>


JS

var app = new Vue({
    el: '#app',
    data: {
        reports: [],
        selectedReport: null
    },
    methods: {

        renderReports: function () {
            var vm = this;

            axios.get('api/Report/Reports')
                .then(function (response) {
                    vm.reports = response.data;

                }, function (error) {
                });
        }
    },
    mounted: function () {
        this.renderReports();

    }
})



Demo





Reference





沒有留言:

張貼留言