locked
cannot get parameters from ajax call to controller razor RRS feed

  • Question

  • User568205723 posted

    Simple usecase - get PartialView dynamically from AJAX call to update div in my main page after input select (dropdownlist) changed value.

    Steps I took:

    1. Created view (only, wihtout PageModel) with model declared with @model ViewModelCreateOperation.
    2. Created checkbox on main page:
    <select class="form-control" asp-items="@(new SelectList(Model.allExistingOperations))" onchange="PopulateForm(this.value); return false;"></select>
    1. created scripts on main page:
    <script>
    
        function PopulateForm(value) {
            var dataToPost = "{ operationName:" + value + "}";;
                $.ajax({
                    type: "post",
                    url: '@Url.Content("/MeaningOfLifeRoutedName")',
                    data: dataToPost ,
                    contentType : 'application/json; charset=UTF-8',
                    success: function (data) {
                        $('#lubieplacki').html(data);
                    },
                    error: function (xhr, ajaxOptions, thrownError) {
                        if (xhr.status == 404) {
                            alert(thrownError);
                        }
                    }
                });
            }
    </script>
    1. created Controller in Controllers folder to return PartialView (becouse I cannot use "return PartialView("someview", someModel)" with PageModel already used as a inherit class.
    namespace MyMysteriousApplication.Controllers
    {
        [Route("MeaningOfLifeRoutedName")]
        public class MeaningOfLifeChangesController : Controller
        {
            private readonly MyMysteriousApplication.Models.TTSCDBContext _context;
    
            public MeaningOfLifeChangesController(MyMysteriousApplication.Models.TTSCDBContext context)
            {
                _context = context;
            }
    
            public ViewModelCreateOperation viewModelCreateOperation { get; set; }
    
         
            public IActionResult Index()
            {
                return RedirectToPage("../Index");
            }
    
    
            [HttpPost]
            public ActionResult getMeaningOfLife(string operationName)
            {
                viewModelCreateOperation = new ViewModelCreateOperation();
    
    
                viewModelCreateOperation = new ViewModelCreateOperation();
                viewModelCreateOperation._entitiesSelectListItem = _context.Entities
                                                                      .Select(a => new Microsoft.AspNetCore.Mvc.Rendering.SelectListItem()
                                                                      {
                                                                          Value = a.Id.ToString(),
                                                                          Text = a.EntityName
                                                                      }).OrderByDescending(u => u.Text)
                                                                      .ToList();
    
    
    
                viewModelCreateOperation.MeaningOfLifeChanges = _context.MeaningOfLifeChanges.Where(u => u.OperationName.Contains(operationName)).OrderBy(u => u.ChangeId).FirstOrDefault();
    
    
    
                return PartialView("../projectManagement/partialViewCreateNewMOL", viewModelCreateOperation);
            }
    
    
        }
    
    }

    Primary question: I got null in parameters - I don't get why: enter image description here

    Bonus question: I couldn't invoke my controller in any way (tried "/MeaningOfLifeChangeController/getMeaningOfLife" or "/MeaningOfLifeChange/getMeaningOfLife", with "~/MeaningOfLifeChangeController/getMeaningOfLife" and others combinations), so I added [Route("MeaningOfLifeRoutedName")] and [HttpPost] before method. I don't get why... in Startup I have added controllers to initialize (JSON is for other stuff(API)):

    services.AddControllersWithViews().
             AddJsonOptions(options =>
             {
                 options.JsonSerializerOptions.PropertyNameCaseInsensitive = true;
                 options.JsonSerializerOptions.PropertyNamingPolicy = null;
                 options.JsonSerializerOptions.MaxDepth = 150;
             }).AddRazorRuntimeCompilation();

    Monday, August 31, 2020 7:33 PM

Answers

  • User-17257777 posted

    Hi lukasz.chrzanowski,

    Since the data  you want to send is just a string type data, you need to stringify it like below.

    var dataToPost = JSON.stringify(value);

    Then in your Action, you should also add [FromBody] attribute.

    public ActionResult getMeaningOfLife([FromBody]string operationName)

    Best Regards,

    Jiadong Meng

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, September 1, 2020 2:36 AM

All replies

  • User-474980206 posted

    your post data is not in a valid in valid json format. as jquery defaults to a url encoded form post, use one its supported formats.  remove contentType and change to:

    var dataToPost = { operationName: value };

    or create valid json:

     

    var dataToPost = JSON.stringify({ operationName: value });

    Tuesday, September 1, 2020 1:32 AM
  • User-17257777 posted

    Hi lukasz.chrzanowski,

    Since the data  you want to send is just a string type data, you need to stringify it like below.

    var dataToPost = JSON.stringify(value);

    Then in your Action, you should also add [FromBody] attribute.

    public ActionResult getMeaningOfLife([FromBody]string operationName)

    Best Regards,

    Jiadong Meng

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, September 1, 2020 2:36 AM
  • User568205723 posted

    Yes! that's it!

    Thank You very much.

    Maybe You know answer to Bonus Question? :)

    Tuesday, September 1, 2020 1:12 PM