views:

80

answers:

2

I've got this in my controller:

    [HttpPost]
    public void UpdateLanguagePreference(string languageTag)
    {
        if (string.IsNullOrEmpty(languageTag))
        {
            throw new ArgumentNullException("languageTag");
        }

        ...
    }

And have this jQuery code POSTing to the controller:

           jQuery.ajax({
                type: 'POST',
                url: '/Config/UpdateLanguagePreference',
                contentType: 'application/json; charset=utf-8',
                data: '{ "languageTag": "' + selectedLanguage + '" }'
            });

When I try to the code, however, I get the error:

Server Error in '/' Application.
Value cannot be null.
Parameter name: languageTag

What's the problem? Isn't this how to POST JSON to an MVC Controller? I can examine the POST using Fiddler and see that the request is correct. For some reason, UpdateLanguagePreference() is getting a null or empty string.

A: 

hmm....

I do it

 $.post(target,
         {
             "ProblemId": id,
             "Status": update
         }, ProcessPostResult);

with

public class ProblemReportUpdate
    {
        public int ProblemId { get; set; }
        public string Status { get; set; }
    }

and

 [HttpPost]
 public ActionResult UpdateProblemReport(ProblemReportUpdate update)

the target is set by

var target = '<%=Url.Action("UpdateProblemReport", "ProblemReport") %>
Keith Nicholas
+1  A: 

You are posting a string and not a JSONified object.

data: '{ "languageTag": "' + selectedLanguage + '" }'

should be

data: { "languageTag": selectedLanguage }

And make sure selectedLanguage is defined within the scope of your ajax call.

Bora
Hmm that's actually not it. A JSONified object is a string. There is no different between the string I'm posting and a JSONified object with a member named "languageTag".
JamesBrownIsDead