Anup
Anup

Reputation: 9738

MVC C# - AJAX Passing 2 Models to Controller

Following is my relevant Code. I want to pass 2 Models to the POST Method.

How to pass 2 Models to Controller?

var mod1 = [], mod2 = [];
mod1.push({
    Server: Server,
    Name: Name                 
});

mod2.push({
    POP: POPServer,
    ....
});

Settings = JSON.stringify({ 'Settings ': mod1 });

jq.ajax({
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    type: 'POST',
    url: '/Site/insertSettings',
    data: Settings ,
    success: function () {
        ....
    }
});

Controller

[HttpPost]
public JsonResult insertSettings(Settings mod1, OtherSettings mod2)
{
    ....
}

Upvotes: 1

Views: 1938

Answers (1)

Guillermo Oramas R.
Guillermo Oramas R.

Reputation: 1303

My approach in this kind of situations is just to create a model that contains both models. It will be something like this:

public class InsertSettingsViewModel()
{
    public Settings settings { get; set; }
    public OtherSettings otherSettings { get; set; }
}

So your controller is going to receive as a parameter the big object:

[HttpPost]
public JsonResult insertSettings(InsertSettingsViewModel model)
{
    //Here you manipulate your objects
}

And your JS action is going to provide the object

var bigMod = [];
var mod1 = [], 
var mod2 = [];
mod1.push({
    Server: Server,
    Name: Name                 
});

mod2.push({
    POP: POPServer,
    ....
});
bigMod.push({
    settings: mod1,
    otherSettings : mod2
})

Settings = JSON.stringify({ 'model': bigMod });

This way is a cleaner code, and I really don't think you could pass a controller various objects. Hope it helps.

Upvotes: 3

Related Questions