string is empty after is post with jquery post in MVC controller

Viewed 23

I want to post a string to the MVC controller and return a partial view. The view returns but the string shows empty. My controller:

public PartialViewResult CreateServiceRateModal(string serviceId)
    {
        System.Diagnostics.Debug.WriteLine(serviceId);
        //var a = JsonSerializer.Serialize();
        ViewData["ServiceId"] = serviceId;
        return PartialView("~/Views/ServicesManager/_CreateServiceRate.cshtml");
    }

Jquery:

function CreateServiceRateModal() {
var Id = $('#ServiceId').val();    
$.post('CreateServiceRateModal', JSON.stringify(Id)).done(function (data) {
    $('#modal-placeholder').html(data);
    $('#modal-placeholder').find('.modal').modal('show');
});

I have checked the Id before posting is not empty.

1 Answers

You need to pass it with a property name matching your controller method parameter name as an object, so change it to this, you can read more on the documentation (https://api.jquery.com/jquery.post/):

$.post('CreateServiceRateModal', { serviceId: Id }).done(function (data) {
  $('#modal-placeholder').html(data);
  $('#modal-placeholder').find('.modal').modal('show');
});
Related