【问题标题】:How to dynamically retrieve data from the database for the Javascript code in ASP.NET MVC 5?如何从数据库中动态检索 ASP.NET MVC 5 中 Javascript 代码的数据?
【发布时间】:2017-04-12 23:15:07
【问题描述】:

我正在构建一个 ASP.NET MVC 5 应用程序,我对这项技术还很陌生。我会非常感谢每一条建议,因为我遇到了困难。

我正在构建一个记忆游戏。我已经构建了游戏的 JavaScript 代码,游戏作为独立代码运行,具有静态定义的游戏卡片/图像数组。但现在我想将它放入 MVC 应用程序的结构中,并从数据库中检索卡片。

型号:

using System;
using System.Web.Mvc;
using System.ComponentModel.DataAnnotations;

namespace SmartBunnyApp.Models
{
    public class Word
    {

        public int WordId { get; set; }
        public string EnglishWord { get; set; }
        public string PolishTranslation { get; set; }
        public string Category { get; set; }
        public byte[] ImageData { get; set; }
        public string ImageMimeType { get; set; }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using SmartBunnyApp.Models;

namespace SmartBunnyApp.Models
{
    public class WordsListViewModel
    {
        public IEnumerable<Word> Words { get; set; }
        public PagingInfo PagingInfo { get; set; }
        public string CurrentCategory { get; set; }
        public byte[] ImageData { get; set; }
    }
}

控制器:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SmartBunnyApp.Abstract;
using SmartBunnyApp.Models;

namespace SmartBunnyApp.Controllers
{
    public class WordController : Controller
    {
        private IWordRepository repository;
        public int PageSize = 4;

        public WordController(IWordRepository wordRepository)
        {
            this.repository = wordRepository;
        }

        public ViewResult List(string category, int page = 1)
        {

            WordsListViewModel viewModel = new WordsListViewModel
            {
                Words = repository.Words
                    .Where(p => category == null || p.Category == category)
                    .OrderBy(p => p.WordId)
                    .Skip((page - 1) * PageSize)
                    .Take(PageSize),
                PagingInfo = new PagingInfo
                {
                    CurrentPage = page,
                    ItemsPerPage = PageSize,
                    TotalItems = category == null ?
                        repository.Words.Count() :
                        repository.Words.Where(e => e.Category == category).Count()
                },
                CurrentCategory = category
            };
            return View(viewModel);
        }

        public IEnumerable<Word> GetAllWords()
        {
            return repository.Words;
        }

        public FileContentResult GetImage(int wordId)
        {
            Word word = repository.Words.FirstOrDefault(p => p.WordId == wordId);
            if (word != null)
            {
                return File(word.ImageData, word.ImageMimeType);
            } else
            {
                return null;
            }
        }
    }
}

现在我需要 JavaScript(或者我已经知道的)jQuery 代码,这将帮助我从数据库中检索所选类别的单词及其图像,并将它们放入一个简单的多维表中,例如这个:

var memory_matching_array = [['dog.jpg','DOG],['penguin.jpg','PENGUIN']];

我尝试按照某人在下面评论中建议的方式实现它,但我不断收到错误消息。特别是我必须在 jQuery 函数中给出 URL 的部分对我来说很难(我不知道这个 URL 应该是什么样子),然后是我必须将数据放入表中以使其看起来像的部分我在上面粘贴的那个。

非常感谢大家的帮助!

【问题讨论】:

标签: javascript c# sql-server asp.net-mvc asp.net-mvc-5


【解决方案1】:

如果您已将数据存储在数据库中(不确定您提到的 table words),您可以创建一个 Web API 控制器并在其中创建一个 get 方法,该方法将返回您所需的数据。

我提到 API 控制器的原因是因为它更容易与 javascript 集成,因为您需要创建视图和模型,并且完成工作所需的工作量更高,但可行。

您需要一个类来表示要从服务器返回的数据结构。

举个例子:

public class Card
{
    public int Id { get; set; }
    public string Name { get; set; }
}

那么你的控制器可以是这样的:

using ProductsApp.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web.Http;

namespace App.Controllers
{
    public class CardsController : ApiController
    {
        Card[] cards = new Card[] 
         { 
            new Product { Id = 1, Name = "Card 1"}, 
            new Product { Id = 2, Name = "Card 2"}
        };

        public IEnumerable<Card> GetAllCards()
        {
            return cards;
        }

        public IHttpActionResult GetCardById(int id)
        {
            var card = cards.FirstOrDefault((p) => p.Id == id);
            if (card == null)
            {
                return NotFound();
            }
            return Ok(card);
        }
    }
}

当然,您可能会从数据库或其他地方读取卡片,但这不是重点。

下一步是通过从您的 JS 代码中调用该方法来获取它们。最简单的方法是使用 JQuery 并像这样进行 ajax 调用:

function GetAllCards() {
    $.ajax({
        url: 'http://{Server Address}/{WebAppName}/api/Cards',
        type: 'GET',
        dataType: 'json',            
        success: function (data) {                
            //do something with data
        },
        error: function (error) {
            //log or alert the error
        }
    });        
}

如果你想使用get by id方法:

function GetCardById(id) {      
    $.ajax({
        url: 'http://{Server Address}/{WebAppName}/api/Cards/'+id,
        type: 'GET',
        dataType: 'json',
        success: function (data) {
            //do something
        },
        error: function (error) {
            //log or alert the error
        }
    });
}

【讨论】:

  • 非常感谢您的评论!您当然向我展示了正确的方向,但我仍然无法继续,因为我不断收到错误响应,而不是从这个函数中获得成功。那么请您查看我编辑过的帖子并尝试再帮我弄清楚吗?
  • 你不是从 ApiController 继承的,所以你的控制器是 MVC,你需要视图来处理你的方法
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-07-28
  • 2023-03-11
  • 1970-01-01
  • 1970-01-01
  • 2012-11-12
  • 1970-01-01
  • 2020-03-18
相关资源
最近更新 更多