Posting JSON to the controller

I have this in the controller:

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

        ...
    }

And add this jQuery POSTing code to the controller:

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

However, when I try to execute the code, I get an error message:

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

What is the problem? Isn't that like POST JSON for an MVC controller? I can check the POST with Fiddler and make sure the request is correct. For some reason, UpdateLanguagePreference()gets an empty or empty string.

+5
source share
4 answers

A warning is very important, even in MVC3, about how MVC3 works.

If you pass an object, for example:

​{
    Test: 'Hi'
}

And the host class:

public class MyModel
{
    public string Test { get; set; }
}

Using a receive controller, for example:

[HttpPost]
public JsonResult Submit(MyModel model)
{
    . . .

. , , :

[HttpPost]
public JsonResult Submit(MyModel test)
{
    . . .

. , MVC JSON , , , , , ( "" / "" ). "", Test, "test", , .

, , , MyModel, , , , . , ( , / ). null , , .

, , , MVC... , - .

(, ..), , , - , , ---a-property-name, :

[HttpPost]
public JsonResult Submit(MyModel _$_$twinkleTwinkleLittleFuckIt)
{

, ModelBinder/JsonValueProviderFactory, 0 , .

+7

....

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

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

 [HttpPost]
 public ActionResult UpdateProblemReport(ProblemReportUpdate update)

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

, JSONified.

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

data: { "languageTag": selectedLanguage}

, selectedLanguage ajax.

+1

jQuery $.ajax() javascript, / . json-, , mvc/mvc2 .

, . JsonValueProviderFactory, MVC2 Futures/MVC3 Beta. :

http://haacked.com/archive/2010/04/15/sending-json-to-an-asp-net-mvc-action-method-argument.aspx

... , , , JsonValueProviderFactory , .

+1
source

All Articles