开发者

MVC JsonResult Method not accepting parameter

I have an MVC JsonResult Method that accepts one string parameter:

    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}, JsonRequestBeha开发者_Go百科vior.AllowGet);
    }

With a jquery method calling the method:

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

However, the JsonResult seems to only receive a null parameter. Even though Firebug is showing that a parameter is being passed:

JSON countryId "11" Source {countryId:'11'}

Any ideas? Thanks


I think the problem is in how you are actually passing the data, you are doing so as a string:

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

When in reality, you should be using a structure on the client side;

data: { countryId: countryId },

jQuery should be able to handle passing the id correctly then. As you are doing it now, it is trying to send JSON to the server, which is not what MVC is expecting, it's expecting a POST with name/value pairs.

You might also want to consider the jQuery Form Plugin, as it makes serializing your Javascript structures into POST data very easy.


Ah, after much searching I've discovered the reason why it fails.

Nothing to do with malformed JSON etc, but rather the fact that the controller method doesnt know what to expect if you try to pass it JSON values:

http://www.c-sharpcorner.com/Blogs/BlogDetail.aspx?BlogId=863

So in my case, I've just elected to pass it a single string value.

        $("#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)
                }
            });


Here I suggest you to decorate your action with HttpPost attribute Like :-

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


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++) {

            });

    }

Try this, it worked for me jQuery function success :function(Destinations)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜