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

Model层Region.cs

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

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

<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

展示效果

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

补充不能获取post的问题解决方式

methods: {
            fun() {
                var f = new FormData();//**这里
                f.append('id', this.id);//**这里
                axios.post("/Default/GetJson", f)
                    .then(res => (this.response = res.data));
                console.log(this.response);
            }
        }
posted @ 2020-01-15 22:01  liessay  阅读(888)  评论(0编辑  收藏  举报