0

I am building an ASP.NET MVC 5 application and I am pretty new to this technology. I would be very thankful for every piece of advice, because I got stuck.

I am building a Memory Game. I have already built the JavaScript code of the game and the game works as a standalone code with statically defined array of cards/images for the game. But now I want to put it into the structure of the MVC application, with the cards retrieved from the database.

Model:

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; }
    }
}

Controller:

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;
            }
        }
    }
}

And now I need to have the JavaScript (or as I already got to know) jQuery code, that will help me retrieve the words and their images from the database for the chosen category and put them into a simple multidimensional table, like this one:

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

I tried to implement it the way that someone suggested in the comment below, but I keep getting an error. Especially the part where I have to give the URL in the jQuery function is hard for me (I have no idea how this URL should look like exactly) and then the part when I have to put the data into a table to make it look like the one that I pasted above.

Thank you guys very much for help!

1

1 Answer 1

1

If you have stored your data in a DB (not sure about table words you mentioned), you can create a web API controller and within that create a get method which will return your desired data.

The reason I mentioned API controller is because it is easier to integrate with javascript since you need to create a view and model and the amount of work required to get the job done is higher, but doable.

You will need a class to represent your data structure to be returned from server.

As an example:

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

Then your controller can be like this:

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);
        }
    }
}

Of course you might read the cards from a DB or something but that's not the point here.

Next step is to get those by calling that method from your JS code. Easiest way is to use JQuery and do an ajax call like this:

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
        }
    });        
}

If you want to use get by id method:

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
        }
    });
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much for your comment! You certainly showed me the right direction but I still can't proceed since I keep getting error response instead of success from this function. So could you please review my edited post and try to help me figure it out one more time?
You are not inheriting from ApiController so your controller is MVC and you need views to deal with your methods

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.