tcode
tcode

Reputation: 5105

Post Value To MVC Action Using JQuery

I have the following JQuery code which retrieves the value from a hidden text box within my MVC 5 Razor View once a submit button is clicked.

$('#mySubmit').click(function() {

    //Get the id to delete from the hidden field
    var id = $('#item-to-delete').val();

    window.location.href = "/CSurvey/Delete/" + id;

});

I then want to POST this value to a HttpPost Action within my Controller. I have tried the code above but it states it cannot find the page and I think this is because my redirect to the Controller Action is incorrect.

[HttpPost]
public ActionResult Delete(int AssessorID)
{
    //delete code
}

Does anyone know of another way to pass the value to the Controller Action?

Thanks.

Upvotes: 0

Views: 1005

Answers (5)

vini
vini

Reputation: 4722

        $("#DeleteBtn").click(function () {
            $.ajax({
                type: "POST",
                url: "/CSurvey/Delete/",
                data: { id: $("#id").val() }


            }).done(function (msg) {
                 alert(msg);
                location.reload();



            });
        })

You can pass your Id and then delete using Jquery.

Upvotes: 1

codebased
codebased

Reputation: 7073

You probably need to use: $('#form').serialize()

Please refer here: http://www.yourinspirationweb.com/en/how-and-when-to-use-jquerys-serialize-method/

Upvotes: 0

noobed
noobed

Reputation: 1339

you can try the following code:

$.ajax({
  type: "POST",
  url: "/CSurvey/Delete",
  contentType: "application/json; charset=utf-8",
  data: {AssessorID=id},
  success: function() { window.location.href = "to/where/you/like"},
});

Upvotes: 3

Johan
Johan

Reputation: 35194

Prefarably, you would like to send a DELETE request to the server.

However, since you're using a <form>, you'll only have access to GET and POST. A html forms default method is POST. Thus, we need to specify GET explicitly:

<form method="GET">
    <input type="text" id="item-to-delete"/>
    <input type="submit"/>
</form>
$('form').on('submit', function(e){

    e.preventDefault(); // don't submit the form... yet

    var $this = $(this),
        id = $this.find('#item-to-delete').val();

    if(!+id) return; // get the id and make sure it's an integer

    $this.prop({ action: '/CSurvey/Delete/' + id }); // set the form action

    $this.submit(); // submit the form with the correct action
});

Upvotes: 2

Nilesh Gajare
Nilesh Gajare

Reputation: 6398

try this

instead of post use get since you are not posting any data

[HttpGet]
public ActionResult Delete(int AssessorID)
{
    //delete code
}

Upvotes: 0

Related Questions