【问题标题】:ASP .net core endpoint configurationASP .net 核心端点配置
【发布时间】:2020-04-25 20:38:09
【问题描述】:

我有一个关于在 ASP .Net 核心中配置端点的问题。
我在控制器中有操作 - HttpGet JsonResult GetList()。它返回 json 字符串,将其显示在视图中,并且 json 字符串在网络响应中,所以我可以通过 JS 访问它。
那是我的 GetList():

[HttpGet]
        public JsonResult GetList(int GetListId)
        {
            SavedList = GetListId;
            List<string> Products = new List<string>();
            List<string> currentList = new List<string>();
            using (var db = new ApplicationDbContext())
            {
                currentList = db.ProductLists.Where(w => w.ListId == GetListId).Select(p => p.Product.Name).ToList();
                foreach (var item in currentList)
                {
                    Products.Add(item);
                }
            }
            List<OfflineProduct> ListToCache = new List<OfflineProduct>();
            JsonSerializer serializer = new JsonSerializer();
            for (int i = 0; i < currentList.Count; i++)
            {
                var Prod = new OfflineProduct();
                Prod.ID = i;
                Prod.Name = currentList[i];
                Prod.Done = false;
                ListToCache.Add(Prod);
            }
            string json = JsonConvert.SerializeObject(ListToCache);

            return Json(json);
        }

我正在从数据库中获取一些元素,并基于它创建列表。将数据序列化为 json,然后返回。问题是,我在页面上获取 JSON 字符串,数据格式不正确。
我有 Vue View,准备获取这个 JSON 数据,但我不知道如何将数据直接发送到 Vue View(例如 ./wwwroot/SavedOfflineList.html)。


我的 Vue vue 已经过测试,我的意思是我将它用于静态数据。这是我的看法:

   <h4>Last Saved List</h4>


    <div id="app">
        <h2>Lista vue:</h2>
        <ol>
            <li v-for="item in items">
                <label>
                    <input type="checkbox"
                           v-on:change="toggle(item)"
                           v-bind:checked="item.Done">

                    <del v-if="item.Done">
                        {{ item.Name}}
                    </del>
                    <span v-else>
                        {{ item.Name }}
                    </span>
                </label>
            </li>
        </ol>
    </div>
</body>

<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
    var objArray = [];
    async function fetchItems() {
        fetch('/GetList/').then(Response => {
            return Response.json();
        }).then(data => {




            for (var i = 0; i < data.length; i++) {
            var newObj = { Name: data[i].Name, ID: data[i].ID, Done: data[i].Done };

            objArray.push(newObj);

                    }
            if (objArray.length != 0) {
                        console.log('have some items');
            }


            console.log(objArray);

        return objArray;   
        }).catch(err => {
            console.log(err);
        })

    }
    new Vue({
        el: "#app",
        data: {
            items: [

            ]
        },
        created() {
            this.getItems();
        },
        methods: {
            toggle: function (item) {
                item.Done = !item.Done
            },
            getItems: async function () {
                this.items = await fetchItems();
                this.items = objArray;
            }
        }
    });




</script>
<style>

当我移动到这个 GetList 页面时,我的 URL 类似于:/Offline/GetList?GetListId=36,并且我可以从响应或页面内容中读取我提到的 json 数据。

我已经阅读了一些关于端点的文章,但我仍然不知道如何将 HttpGet 从 wwwroot 发送到 html 视图。

我已经在静态文件上对其进行了测试,并且可以正常工作:


感谢您的阅读和帮助!

【问题讨论】:

  • 你能更好地解释你的问题吗?
  • 问题在于实现 Vue 组件,它会为我呈现 json。此刻,当我单击按钮时,我只是得到了 json 字符串。 GetList() 是 View 中的 onclick 事件。当我点击它时,它应该取 List,将它序列化为 json 并使用这个 json 来创建视图。
  • 我已经添加了屏幕应该如何工作,当它得到好的 json 时

标签: javascript json vue.js asp.net-core


【解决方案1】:

您可以直接返回 ListToCache 而无需额外的序列化。

[HttpGet]
public JsonResult GetList(int GetListId)
    {
        SavedList = GetListId;
        List<string> Products = new List<string>();
        List<string> currentList = new List<string>();
        using (var db = new ApplicationDbContext())
        {
            currentList = db.ProductLists.Where(w => w.ListId == GetListId).Select(p => p.Product.Name).ToList();
            foreach (var item in currentList)
            {
                Products.Add(item);
            }
        }
        List<OfflineProduct> ListToCache = new List<OfflineProduct>();

        for (int i = 0; i < currentList.Count; i++)
        {
            var Prod = new OfflineProduct();
            Prod.ID = i;
            Prod.Name = currentList[i];
            Prod.Done = false;
            ListToCache.Add(Prod);
        }

        return Json(ListToCache);
    }

这将生成json响应。另外,获取响应数据的属性名称区分大小写。你最好检查json,一般情况下,它会

var newObj = { Name: data[i].name, ID: data[i].id, Done: data[i].done }

【讨论】:

  • 好的,我已经添加了新的 cshtml 视图,我正在调用 GetList 方法。我有 jsonData 作为回应。
【解决方案2】:

你能尝试用这个替换你的脚本标签吗?

<script>
    new Vue({
        el: "#app",
        data: {
            items: []
        },
        created() {
            this.getItems();
        },
        methods: {
            toggle: function (item) {
                item.Done = !item.Done
            },
            getItems() {
                fetch('/GetList/').then(response => response.json())
                .then(data => this.items = data)
                .catch(err => console.log(err));
            }
        }
    });
</script>

检查检查器中的网络选项卡,检查服务器是否响应了您想要的。

【讨论】:

  • 问题是,我的脚本不适用于动态数据。我的意思是当我点击列表旁边的按钮时,我得到“/Offline/GetList?GetListId=36”这个url,并且没有vue什么的。
猜你喜欢
  • 2018-10-17
  • 2018-11-24
  • 2017-04-17
  • 2017-03-22
  • 1970-01-01
  • 2020-09-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多