frankclaassens
frankclaassens

Reputation: 1930

Posting model from MVC to action using jquery post

I'm trying to post my model to an MVC Action, using jquery post. In MVC, I'm doing the following to serialise my model to JSON:

MVC:

<div class="myModel" hidden="true">@Html.Raw(Json.Encode(Model))</div>

Javascript:

$(".confirm_yes").click(function (e) {
    e.preventDefault();

    // Get credit card session id
    var sessionid = $(this).parent().find(".payu_creditcard_sessionid").text();

    var myModel = $(".myModel").text();
    $.post("/payuwalletlink/removecreditcard", { model: myModel }, function (data) {

        //do whatever with the returned view.

    });
});

Controller:

[HttpPost]
public ActionResult RemoveCreditCard(CreditCardModel model)
{

    return View("PayUwallet");
}

But I get the following error from my browser:

Failed to load resource: the server responded with a status of 500 (Internal Server Error)

Upvotes: 0

Views: 1137

Answers (1)

user3559349
user3559349

Reputation:

What you seem to be doing makes no sense. Why would you pass a model to a view and then post it completely unchanged?. However, the way to do this if needed, is to convert the model to a javascript object and post it back

var myModel = JSON.parse('@Html.Raw(Json.Encode(Model))');

$(".confirm_yes").click(function (e) {
  e.preventDefault();
  // Get credit card session id
  var sessionid = $(this).parent().find(".payu_creditcard_sessionid").text();     
  $.post('@Url.Action("removecreditcard", "payuwalletlink")', myModel , function (data) {
    ....
  });
});

Not sure what var sessionid = .. is for (you don't seem to use it).

I suspect what your trying to is delete an object on the post method, in which case, just pass back the ID of the object.

Upvotes: 2

Related Questions