【Vue】通过axios实现与asp.net后台数据传递(图文+代码示例)

注意前提:需要在同一个C#项目(asp.net)中,否则会出现跨域问题。

Home.html代码

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title></title>
    <script src="Content/vue.js"></script>
    <script src="https://cdn.staticfile.org/axios/0.18.0/axios.min.js"></script>
</head>

<body>
    <div id="box">

        ---- Vue数据列表 ---- <br>
        <ul>
            <li v-for="p in persons" :key="p.id">
                {
   
   {p.id}} {
   
   {p.name}}-{
   
   {p.age}}岁
                <button @click="submit(p.id)">提交后台获取ID值</button>
            </li>

        </ul>

    </div>
    <script type="text/javascript">
        var box = new Vue({
            el: "#box",
            data: {
                persons: [
                    {
                        id: "1",
                        name: "张飞",
                        age: 20
                    },
                    {
                        id: "2",
                        name: "刘备",
                        age: 30
                    },
                    {
                        id: "3",
                        name: "吕布",
                        age: 22
                    }
                ]
            },
            mounted() {
                axios
                    .get('/Home/ListJson')
                    .then(response => (this.persons = response.data))
                    .catch(function (error) { // 请求失败处理
                        console.log(error);
                    });
            },
            methods: {
                submit(a) {
                    alert("把当前记录ID:[" + a + "]提交给后台.");
                    axios
                        .post('/Home/SubmitJson', {
                            paramA: a
                        })
                        .then(response => (alert(response.data)))
                        .catch(function (error) { // 请求失败处理
                            console.log(error);
                        });
                }
            }

        })
    </script>

</body>

</html>

猜你喜欢

转载自blog.csdn.net/dxnn520/article/details/124625224
今日推荐