Sami
Sami

Reputation: 3800

MVC JsonResult Controller parameter null

HTML

 <a href="@item.documentId" class="glyphicon glyphicon-remove-circle del-file"></a>

JavaScript

$(".del-file").click(function () {
        alert($(this).attr('href'));
        var jsonData = "{'doc':'" + $(this).attr('href') + "'}";

        var parent_row = $(this).closest('tr');

        $.post('@Url.Action("Delete","Documents")', jsonData)
            .success(function (response) {
                if (response.result == true) {
                    $(parent_row).remove();
                }
            })
            .error(function (jqXHR, textStatus, errorThrown) {
                if (jqXHR.status == 500) {
                    alert('Internal error: ' + jqXHR.responseText);
                } else {
                    alert('Unexpected error.');
                }
            })
        return false;
    })

MVC Controller Method

public JsonResult Delete(string doc)
    {            
        long docId = Helpers.Utility.Instance.getIdAfterDecode(doc);            
        if (docId <=0)
        {
            return Json(new { result = "error: Document info was not correct." });
        }
        bool output = new DocumentsInfoRepository().deleteDocument(docId);
        return Json(new { result = output});
    }

doc is always null, what am I missing. Please advice. Thanks

Upvotes: 0

Views: 129

Answers (1)

The problem is in your json constrruction you have to construct like this.

 var jsonData = {doc:$(this).attr('href')};

as you are sending a post request to an action it's better to add [HttpPost] attribute on actions.

    [HttpPost]
    public JsonResult Delete(string doc)

Upvotes: 1

Related Questions