3

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}, JsonRequestBehavior.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

1
  • FWIW, "{countryId:'" + countryId + "'}" isn't JSON. JSON requires double quotes. You should really use something like json.org/json2.js to serialize objects to JSON format Commented May 10, 2010 at 15:57

4 Answers 4

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

when I look at the POST request in Firebug, it is passing a name/value pair. And this very same way of passing parameters works when I call a webservice (as opposed to calling an MVC method)
1

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

Comments

0

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

Comments

0
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)

Comments

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.