2

Why TestData does not receive anything?

POST http://localhost:46628/Home/TestData 500 (Internal Server Error)

index.cshtml:

@{
ViewBag.Title = "Index";
}

<h2>Index</h2>

<script src="~/Scripts/knockout-2.2.0.js"></script>
<button data-bind="click: sendata">send data</button>
<script>
function MyViewModel() {
    var self = this;
    self.sendata = function () {
        $.ajax({
            type: 'POST',
            url: 'Home/TestData',
            contentType: 'application/json; charset=utf-8',
            data: { json: 'json', date: 'date' },
            dataType: 'json'
        });
    }
}
ko.applyBindings(new MyViewModel());
</script>

Controller:

public class HomeController : Controller
{
    //
    // GET: /Home/

    public ActionResult Index()
    {
        return View();
    }

    [HttpPost]

    public void TestData(string json,string date)
    {
        Console.WriteLine(json);
    }

}

1 Answer 1

4

You use parameter data like this:

data: { json: 'json', date: 'date' },

Even though you specified that your content type is json, jQuery uses $.param to serialize your data, so instead of sending the json the data is sent like this:

json=json&date=date

Your server though expects json to be provided, so model binding fails.

Instead you should manually serialize the data to json before making AJAX call:

data: JSON.stringify({ json: 'json', date: 'date' }),

The rest of the code seems to be fine.

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

1 Comment

Alternatively, remove the contentType: 'application/json; charset=utf-8', option so it uses the default application/x-www-form-urlencoded; charset=UTF-8

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.