Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass object from JSON into MVC Controller - its always null?

I have seen a few questions on here related to the a similar issue, I have read them, followed them, but still i have the same problem.

I am basically creating an object in javascript and trying to call a method on the controller that will return a string of html. Not JSON.

I've been playing around with dataType and contentType but still no joy. So apologies if the code snippets are a bit messy.

Build the object in JS.

function GetCardModel() {
    var card = {};
    card.CardTitle = $("#CardTitle").val();
    card.TopicTitle = $("#TopicTitle").val();
    card.TopicBody = $("#TopicBody").data("tEditor").value();
    card.CardClose = $("#CardClose").val();
    card.CardFromName = $("#CardFromName").val();
    return card;
}

Take a look at the object - all looks good and as it should in JSON.

var model = GetCardModel();
alert(JSON.stringify(GetCardModel()));

Make the call...

$.ajax({
            type: "POST",
            url: "/Postcard/Create/Preview/",
            dataType: "json",
            //contentType: "application/json",
            data: GetCardModel(),
            processData: true,
            success: function (data) {
                alert("im back");
                alert(data);
            },
            error: function (xhr, ajaxOptions, error) {
                alert(xhr.status);
                alert("Error: " + xhr.responseText);
                //alert(error);
            }
        });

Always when I step into the controller, the object is ALWAYS there, but with null values for all the properties.

like image 629
SteveCl Avatar asked Jan 11 '11 09:01

SteveCl


1 Answers

The parameter name should be data, not date:

$.ajax({
    type: 'POST',
    url: '/Postcard/Create/Preview/',
    dataType: 'json',
    data: {
        CardTitle: $("#CardTitle").val(),
        TopicTitle: $("#TopicTitle").val(),
        TopicBody: $("#TopicBody").data("tEditor").value(),
        CardClose: $("#CardClose").val(),
        CardFromName: $("#CardFromName").val()
    },
    success: function (data) {
        alert('im back');
        alert(data);
    },
    error: function (xhr, ajaxOptions, error) {
        alert(xhr.status);
        alert('Error: ' + xhr.responseText);
    }
});

which will successfully call the following controller action and the action parameter will be properly bound:

[HttpPost]
public ActionResult Preview(Card card) { ... }

with the model below:

public class Card
{
    public string CardTitle { get; set; }
    public string TopicTitle { get; set; }
    public string TopicBody { get; set; }
    public string CardClose { get; set; }
    public string CardFromName { get; set; }
}
like image 69
Darin Dimitrov Avatar answered Nov 19 '22 12:11

Darin Dimitrov