如何调用webservice的次数是foreach循环在页面加载时运行的次数

时间:2015-08-11 16:41:22

标签: c# jquery asp.net-mvc web-services foreach

我正在为数据库中的字母声音调用音频文件。我使用webservice,jquery和c#(foreach)代码来实现这一目标。

在foreach循环中,我调用每个字母完整的单词但发生的事情是web服务在页面加载时调用一次,因此只调用数据库中的第一个字母的声音。这意味着对于单词“Hat”,为3个字母的所有实例调用字母“h”的音频,因为webservice只被调用一次。

C#代码:

string s1 = words[correctImageIndex].engWord;
List<char> ia = s1.ToList();
Random random = new Random(ia.Count);
List<int> selectedIndexes = new List<int>();                             


                         foreach (var letter in ia)
                         {
                             int index = ia.IndexOf(letter);
                             int randomNumber =random.Next(0, ia.Count);
                             while (randomNumber == index || selectedIndexes.Contains(randomNumber))
                             {
                                 randomNumber = random.Next(0, ia.Count);
                             }

                            <img onclick="LetterSound()" src="~/Image/DrawLetters?letter=@ia[randomNumber]">
                             selectedIndexes.Add(randomNumber);
                         }

jquery代码:

function LetterSound() {
                var id = $("[id$=hiddenWord_id]").val();
                $.ajax({

                    url: "../../WebService.asmx/LetterSound",
                    data: "{ 'id': '" + id + "'}",
                    dataType: "json",
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    success: function (data) {

                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {

                    }
                });
            };

Webservice代码:

public void LetterSound(int id)
    {

        using (The_FactoryDBContext db = new The_FactoryDBContext())
        {

                string s1 = db.Words.FirstOrDefault(word => word.wordID == id).engWord;
                char[] ia = s1.ToCharArray();

                foreach (char letter in ia)
                {
                    string letr = letter.ToString();
                    if (db.LetterLands.FirstOrDefault(let => let.letter == letr).letterDescAudio != null)
                    {
                        byte[] bytes = db.LetterLands.FirstOrDefault(let => let.letter == letr).letterDescAudio;

                        MemoryStream ms = new MemoryStream(bytes);
                        System.Media.SoundPlayer myPlayer = new System.Media.SoundPlayer(ms);
                        myPlayer.Play();
                    }

                }
        }
    }

如何确保为foreach循环中的每个字母调用webservice?

0 个答案:

没有答案