MVC3 Passing ViewModel to controller method using JQuery Ajax

后端 未结 3 1681
臣服心动
臣服心动 2021-01-05 15:06

I\'m trying to pass a form\'s data to my controller method using JQuery Ajax, but I\'m not sure how you do this as my ViewModel is null when I use debugger on the Controller

相关标签:
3条回答
  • 2021-01-05 15:18

    The names of the variables in the data that you are posting does not correspond with the names of the properties of your ASP.Net MVC ViewModel, so the data can not be binded properly.

    0 讨论(0)
  • 2021-01-05 15:25

    If you wanted to automatically build the model from the bound view model of a form, you can use the code from this answer https://stackoverflow.com/a/1186309 to properly serialize to a JSON object.

    You'd then need to pass it as a string to your $.ajax call. All in all, very similar to what you originally had. Something like:

    var premisesViewModel = $('form').serializeObject();
    $.ajax({
            url: form.attr('action'),
            type: 'POST',
            dataType: "json",
            contentType: 'application/json',
            data: JSON.stringify(premisesViewModel),
            success: function (data) {
                alert('done');
            }
        });
    

    Quite strange that there's no core function to convert to a JSON object, but there you go.

    0 讨论(0)
  • 2021-01-05 15:30

    Your JSON format exactly same as your model class.

    Current example

    public class PremisesViewModel
    {
    
        public string createPremisesErrorMessage { get; set; }
        public string updatePremisesErrorMessage { get; set; }
    
        public SelectList listOfCounties = Initialise.countiesSelectList;
    
        public Premise premises { get; set; }
    }
    

    Your JSON like

     var premisesViewModel = {
                                        createPremisesErrorMessage : $('#premises_PremisesDescription').val(),
                                        updatePremisesErrorMessage: $('#premises_OrdnanceSurveyReference').val(),    
                                        premises : {Define more properties here as per your Premise structure}
                                    }
    
    0 讨论(0)
提交回复
热议问题