Asp.net MVC Vue Axios无刷新请求数据和响应数据

时间:2021-12-17 18:02:14

Model层Region.cs

Asp.net MVC Vue Axios无刷新请求数据和响应数据Asp.net MVC Vue Axios无刷新请求数据和响应数据
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace WebApplication1.Models
{
    public class Region
    {
        public int Id { get; set; }
        public string City { get; set; }
    }
}
View Code

Controller

Asp.net MVC Vue Axios无刷新请求数据和响应数据Asp.net MVC Vue Axios无刷新请求数据和响应数据
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using WebApplication1.Models;

namespace WebApplication1.Controllers
{
    public class DefaultController : Controller
    {
        //获取Json数据
        [HttpPost]
        public JsonResult GetJson(int id)
        {
            List<Region> regions = new List<Region>() {
                new Region{ Id=0,City="山东省"},
                new Region{ Id=1,City="济南市"},
                new Region{ Id=2,City="历下区"},
                new Region{ Id=3,City="市中区"},
                new Region{ Id=4,City="天桥区"},
                new Region{ Id=5,City="槐荫区"}
            };
            var json = from r in regions where r.Id == id select r;
            return Json(json);
        }
        //显示主页
        public ActionResult Index()
        {
            return View();
        }
    }
}
View Code

View

Asp.net MVC Vue Axios无刷新请求数据和响应数据Asp.net MVC Vue Axios无刷新请求数据和响应数据
<script src="~/Scripts/vue.js"></script>
<script src="~/Scripts/axios.js"></script>
<h2>Index</h2>
<div id="app">
    <hr />
    <input type="number" v-model.number="id" />
    <input type="button" v-on:click="fun()" value="查询" />
    <table border="1">
        <tr>
            <th>编号</th>
            <th>地区</th>
        </tr>
        <tr v-for="item in response">
            <td>{{item.Id}}</td>
            <td>{{item.City}}</td>
        </tr>
    </table>
</div>
<script>
    var vm = new Vue({
        el: "#app",
        data() {
            return {
                response: null,
                id: 0
            }
        },
        methods: {
            fun: function () {
                axios.post("/Default/GetJson", { id: this.id })
                    .then(res => (this.response = res.data));
            }
        }
    });
View Code

展示效果

Asp.net MVC Vue Axios无刷新请求数据和响应数据

不知道为什么Request["id"]获取不到view传过来的请求,用Form表单方式请求没有问题,网上找了一些也没找到怎么回事,GetJson(int id)作为参数可以,暂时这么滴吧