1

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)
{
    ....
}
5
  • 1
    var data = JSON.stringify({'mod1' : mod1, 'mod2': mod2}); ? Commented Mar 13, 2015 at 12:22
  • Really eager to know whether it is possible with MVC as Web-API does not allow this. stackoverflow.com/a/14407502/1505865 Commented Mar 13, 2015 at 12:22
  • 1
    I dont think it works with mutiple complex objects, although maybe a custom binder? the easy way is just make a new object with your two objects in it Commented Mar 13, 2015 at 12:34
  • although, maybe im misinterpreting the question. do you mean pass mod1 OR mod2 Commented Mar 13, 2015 at 12:36
  • I want to pass both..! Commented Mar 13, 2015 at 12:48

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.