AnonyMouse
AnonyMouse

Reputation: 18630

MVC getting null parameter error when posting to controller

I have this method in my mvc controller:

public void RejectInvoice(int invoiceId)
        {
            var invoice = _unitOfWork.InvoiceRepository.Get((int)invoiceId);

            invoice.Rejected = true;
            invoice.RejectedDateTime = DateTime.Now;

            _unitOfWork.InvoiceRepository.InsertUpdate(invoice);
            _unitOfWork.Save();
        }

In my script file I call it using:

$.post('/Invoice/RejectInvoice/'+ 3, function (data) {

                    });

In firebug I'm getting:

enter image description here

What the ...........? It clearly shows I've provided it with the 3 as a parameter but then claims I'm sending it a null?

can someone tell me what is going on here? How to fix?

Upvotes: 0

Views: 486

Answers (2)

coffeeyesplease
coffeeyesplease

Reputation: 1028

If you're doing a post you should also decorated your methods the [HttpPost] attribute and check the sent parameters, my suggestion would be:

[HttpPost]
public void RejectInvoice(FormCollection collection)
{
    var id = -1;
    if(int.TryParse(collection["invoiceId"], out id))
    {
        var invoice = _unitOfWork.InvoiceRepository.Get(id);

        invoice.Rejected = true;
        invoice.RejectedDateTime = DateTime.Now;

        _unitOfWork.InvoiceRepository.InsertUpdate(invoice);
        _unitOfWork.Save();         
    }

}

as for the jquery:

$.post("/Invoice/RejectInvoice/", { invoiceId: "3"}, callback );

(I think, it been a while since I last used $.post)

Upvotes: 0

Tuan
Tuan

Reputation: 5412

The default model binder will bind to a parameter called "id" but your parameter is named invoiceId, so it does not know to bind the value to it. A quick fix would be to change your POST URL to '/Invoice/RejectInvoice/?invoiceId='+ 3.

Upvotes: 4

Related Questions