whodares
whodares

Reputation: 696

jquery needs to use mvc model as parameter

I'm currently working in ASP.NET MVC 4. I'm trying to use JQuery to render a specific part of my page in certain situations. For this I have written the following JQuery code:

var selectedLicense = '@Model.License';

        $.post("/Permission/LicenseConfigurationLabelOrCombobox", selectedLicense,
            function (responseText) { 
                $(".LicenseWizard").html(responseText);
            });

In my controller I have the following Action:

public String LicenseConfigurationLabelOrCombobox(LicenseWithCharacteristicsModel license)
        {
          //Do Stuff
        }

My action model remains to be empty though. In order to try something new, I did the following in my model:

public class PermissionLicenseConfigurationModel
    {
        public LicenseWithCharacteristicsModel License { get; set; }
        public string JsonLicense
        {
            get
            {
                return new JavaScriptSerializer().Serialize(License);
            }
        }
    }

I updated my JQuery as well:

var selectedLicense = '@Model.JsonLicense';

        $.post("/Permission/LicenseConfigurationLabelOrCombobox", selectedLicense,
            function (responseText) { 
                $(".LicenseWizard").html(responseText);
            });

I can see that my JQuery uses a real serialized object, but my action model doesn't pick it up. The Id is always 0 and the values null.

Any hints?

Upvotes: 0

Views: 1102

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

Start by getting rid of this JsonLicense property from your view model:

public class PermissionLicenseConfigurationModel
{
    public LicenseWithCharacteristicsModel License { get; set; }
}

and then inside your view you could send the model as a JSON request to the controller:

var selectedLicense = @Html.Raw(Json.Encode(Model.License));
$.ajax({
    url: '@Url.Action("LicenseConfigurationLabelOrCombobox", "Permission")',
    type: 'POST',
    contentType: 'application/json; charset=utf-8',
    data: JSON.stringify(selectedLicense),
    success: function(result) {
        $(".LicenseWizard").html(result);
    }
});

Upvotes: 1

Related Questions