0

here is my jquery :

$(document).ready(function () {

    $("#GameId").change(function () {

        $.get('/MatchManager/GetMatchType/' + $(this).val(), function (response) {

            var Games = $.evalJSON(response);

            var ddlSelectedProduct = $("#MatchTypeId");

            $("#MatchTypeId > option").remove();

            for (i = 0; i < Games.length; i++) {

                ddlSelectedProduct.append($("<option />").val(Games[i].Value).text(Games[i].Text));

            }
        });

    });

});

I print out the response and its correct, but for some reason my program stops at the $.evalJson and says $.evalJSON is not a function Here is my GetMatchType controller just in case:

public string GetMatchType(int id)
    {
        var ListMatchTypes = new List<SelectListItem>();
        using (var db = new MatchGamingEntities())
        {

            var MyMatchTypes = from m in db.MatchTypes
                               where m.GameId == id
                               select m;
            foreach (var item in MyMatchTypes.ToList())
            {
                ListMatchTypes.Add(new SelectListItem() { Text = item.MatchTypeName, Value = item.MatchTypeId.ToString() });
            }
        }
        return new JavaScriptSerializer().Serialize(ListMatchTypes);

    }

This is my view:

@using (Html.BeginForm()) { @Html.ValidationSummary(true) MatchModel @Html.LabelFor(model => model.GameId) @Html.DropDownList("GameId", new SelectList(ViewBag.MyGames as System.Collections.IEnumerable, "GameId", "GameName"), "Please Select One")

    </div>
    <div class="editor-label">
        @Html.LabelFor(model => model.MatchTypeId)
    </div>
    <div class="editor-field">
        @Html.DropDownList("MatchTypeId", new SelectList(ViewBag.MatchTypes as System.Collections.IEnumerable, "Value", "Text"))

    </div>
    <div class="editor-label">
        @Html.LabelFor(model => model.MatchName)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.MatchName)
        @Html.ValidationMessageFor(model => model.MatchName)
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.MatchDescription)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.MatchDescription)
        @Html.ValidationMessageFor(model => model.MatchDescription)
    </div>



    <div class="editor-label">
        @Html.LabelFor(model => model.Wager)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.Wager)
        @Html.ValidationMessageFor(model => model.Wager) <br />
        <span>Your Current Account Balance: @ViewBag.Balance</span>
    </div>

    <p>
        <input type="submit" value="Create" />
    </p>
</fieldset>

}

@Html.ActionLink("Back to List", "Index")
1
  • What's wrong with $.parseJSON? Commented Mar 21, 2011 at 21:16

4 Answers 4

3

Remarks:

  • Controller actions should always return ActionResults
  • Use JsonResult instead of manually serializing with JavaScriptSerializer
  • You don't need to manually parse with any $.evalJSON on the client => if you followed my previous remark the proper content type application/json will be sent and jQuery will automatically parse the object passed to the success callback.
  • Never hardocode urls in your javascript => always use url helpers when dealing with urls or your code might break when you deploy due to virtual directory added.

This being said let's try to improve your code starting with the controller action:

public ActionResult GetMatchType(int id)
{
    using (var db = new MatchGamingEntities())
    {
        return Json(
            from m in db.MatchTypes
            where m.GameId == id
            select new {
                Text = m.MatchTypeName,
                Value = m.MatchTypeId
            },
            JsonRequestBehavior.AllowGet
        );
    }
}

and then the javascript:

$(function () {
    $('#GameId').change(function () {
        var url = '@Url.Action("GetMatchType", "MatchManager")';
        var data = { id: $(this).val() };
        $.get(url, data, function (games) {
            var ddlSelectedProduct = $('#MatchTypeId');
            ddlSelectedProduct.empty();
            $.each(games, function(index, game) {
                ddlSelectedProduct.append(
                    $('<option/>', {
                        value: game.Value,
                        text: game.Text
                    })
                );
            });
        });
    });
});
Sign up to request clarification or add additional context in comments.

4 Comments

Hey I copied your code exactly and it did not work. I edited my question and added my View.
@anthonypliu, what didn't work? Do you get some error? Is the controller action being hit? When looking with FireBug what does the server respond to the AJAX call? Maybe I did some mistake when typing it.
Hey I checked the firebug and this was the response:An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
@anthonypliu, so what's the exception? What happens when you debug your controller action?
1

Instead of trying to parse the JSON yourself, let jQuery handle it.

Just replace your $.get with $.getJSON

jQuery will then automatically try to decode the response as JSON and you can automatically access it like a plain object.

jQuery.getJSON on the docs.

Comments

0

Did you include http://code.google.com/p/jquery-json/ ?

Comments

0
$(document).ready(function () {
    $("#GameId").change(function () {
        $.getJSON('/MatchManager/GetMatchType/' + $(this).val(), function (Games) {
            var ddlSelectedProduct = $("#MatchTypeId");
            $("#MatchTypeId > option").remove();
            for (i = 0; i < Games.length; i++) {
                ddlSelectedProduct.append($("<option />").val(Games[i].Value).text(Games[i].Text));
            }
        });
    });
});

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.