Метод MVC JsonResult не принимает параметр - PullRequest
3 голосов
/ 10 мая 2010

У меня есть метод MVC JsonResult, который принимает один строковый параметр:

    public JsonResult GetDestinations(string countryId)
    {
        List<Destination> destinations = new List<Destination>();

        string destinationsXml = SharedMethods.GetDestinations();
        XDocument xmlDoc = XDocument.Parse(destinationsXml);
        var d = from country in xmlDoc.Descendants("Country")
                from destinationsx in country.Elements("Destinations")
                from destination in destinationsx.Elements("Destination")
                where (string)country.Attribute("ID") == countryId
                select new Destination
                {
                    Name = destination.Attribute("Name").Value,
                    ID = destination.Attribute("ID").Value,
                };
        destinations = d.ToList();

        return Json(new JsonResult { Data = destinations}, JsonRequestBehavior.AllowGet);
    }

С помощью метода jquery, вызывающего метод:

        //Fetch Destinations
        $("#Country").change(function () {
            var countryId = $("#Country > option:selected").attr("value");
            $("#Destination").html("");
            $("#Resort").html("");
            $("#Resort").append($("<option></option>").val(0).html("---Select---"));
            $.ajax({
                type: "POST",
                traditional: true,                    
                url: "/Destinations/GetDestinations",
                data: "{countryId:'" + countryId + "'}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (msg) {
                    BindDestinationSelect(msg)
                }
            });
        });

Однако JsonResult, похоже, получает только нулевой параметр. Хотя Firebug показывает, что передается параметр:

JSON CountryId "11" Источник {CountryId: '11' }

Есть идеи? Спасибо

Ответы [ 4 ]

1 голос
/ 11 мая 2010

Ах, после долгих поисков я обнаружил причину, по которой это не удалось.

Ничего общего с искаженным JSON и т. Д., А скорее с тем, что метод контроллера не знает, чего ожидать, если вы попытаетесь передать ему значения JSON:

http://www.c -sharpcorner.com / Блоги / BlogDetail.aspx? BlogId = 863

Так что в моем случае я просто решил передать ему одно строковое значение.

        $("#Country").change(function () {
            var countryId = $("#Country > option:selected").attr("value");
            $("#Destination").html("");
            $("#Resort").html("");
            $("#Resort").append($("<option></option>").val(0).html("---Select---"));
            $.ajax({
                type: "POST",
                traditional: true,
                url: "/Destinations/GetDestinations",
                data: "countryId=" + countryId,
                success: function (msg) {
                    BindDestinationSelect(msg.Data)
                }
            });
1 голос
/ 10 мая 2010

Я думаю, что проблема в том, как вы на самом деле передаете данные, вы делаете это в виде строки:

data: "{countryId:'" + countryId + "'}",

Когда на самом деле вы должны использовать структуру на стороне клиента;

data: { countryId: countryId },

jQuery должен уметь правильно обрабатывать передачу идентификатора. Как вы делаете это сейчас, он пытается отправить JSON на сервер, чего не ожидает MVC, а ожидает POST с парами имя / значение.

Возможно, вы также захотите рассмотреть jQuery Form Plugin , поскольку он делает сериализацию ваших структур Javascript в данные POST очень легкой.

0 голосов
/ 01 октября 2013

Здесь я предлагаю вам украсить свое действие атрибутом HttpPost. Нравится: -

[HttpPost]
public JsonResult GetDestinations(string countryId)
{
    List<Destination> destinations = new List<Destination>();

    string destinationsXml = SharedMethods.GetDestinations();
    XDocument xmlDoc = XDocument.Parse(destinationsXml);
    var d = from country in xmlDoc.Descendants("Country")
            from destinationsx in country.Elements("Destinations")
            from destination in destinationsx.Elements("Destination")
            where (string)country.Attribute("ID") == countryId
            select new Destination
            {
                Name = destination.Attribute("Name").Value,
                ID = destination.Attribute("ID").Value,
            };
    destinations = d.ToList();

    return Json(new JsonResult { Data = destinations}, JsonRequestBehavior.AllowGet);
}
0 голосов
/ 01 октября 2013
public JsonResult BindAllData(string Userid)
    {

        List<VoteList> list = new List<VoteList>();
        var indexlist = db.TB_WebSites.ToList();
        int i = 0;
        var countlist = db.Tb_Votes.ToList();
        var VCountList = db.Tb_Votes.ToList();
        foreach (TB_WebSites vt in indexlist)
        {
            bool voted = false;
        }

        return Json(new { List = _list });

    }


    function DataBind() {
        $("#LoadingDatas").show();
        var userid = $("#FBUserId").text();
        //alert('Data : ' + userid);
        var InnerHtml = "";
        $.ajax(
            {
                url: '/Gitex/BindAllData/',
                type: 'POST',
                data: { "Userid": userid },
                dataType: 'json',
                async: true,
                success: function (data) {
                    //alert('Done');
                    //alert(data.List.length);
                    for (var i = 0; i < data.List.length; i++) {

            });

    }

Попробуй, у меня это сработало функция jQuery успех: функция (Направления)

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...