mosquito87
mosquito87

Reputation: 4440

AJAX post to asp.net MVC controller method not working

I have this method in my controller:

[HttpPost]
public ActionResult Create(StatusMessage statusMessage, int foreignKey, int statusMessageType)
{
    //Do something
}

This is how my StatusMessage model looks like:

public abstract class StatusMessage 
{
    [Key]
    public int Id { get; set; }

    /// <summary>
    /// Message
    /// </summary>
    /// [Required]
    public string Description { get; set; }

    public DateTime CreationDate { get; set; }

    public int UseraccountId { get; set; }
    public virtual Useraccount Useraccount { get; set; }
}

And I'd like to send a post via jquery ajax to my controller:

function sendForm(message, foreignKey, statusMessageType, target) {
    var statusMessage = {
      Description: "This is a test message"
    };
    $.ajax({
        url: target,
        type: "POST",
        contentType: 'application/json',
        data: JSON.stringify({
            statusMessage: statusMessage,
            foreignKey: foreignKey,
            statusMessageType: statusMessageType
        }),
        success: ajaxOnSuccess,
        error: function (jqXHR, exception) {
            alert(exception);
        }
    });
}

But the POST isn't sent correctly. Through testing I figured already out that the problem is the StatusMessage class. If I replace it by a string, everything is working fine.

Upvotes: 0

Views: 1440

Answers (2)

Satpal
Satpal

Reputation: 133403

Why you have defined your class as abstract, controller won't be able to create its instance

Define you class as

 public class StatusMessage

for info http://www.codeproject.com/Articles/6118/All-about-abstract-classes

Upvotes: 1

von v.
von v.

Reputation: 17108

Your ajax post is not working because StatusMessage is an abstract class and you (or the controller) cannot create an instance of it. You should either make it a concrete class or derive another class from it.

Upvotes: 0

Related Questions