最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

c# - MVC4 controller post multiple json objects to controller, ajax post - Stack Overflow

programmeradmin1浏览0评论

is there any example to post multiple objects to a controller. How the data for the ajax post have to look like ?

[HttpPost]
public string Register(UserLogin userLogin, Contact contact)
{
}

UserLogin

public class UserLogin 
{
   public string Username { get; set; }
   public string Password { get; set; }
}

Contact

public class Contact
{
   public string Firstname { get; set; }
   public string Lastname { get; set; }
}

AJAX ?

$.ajax({
   type: "POST",
   url: "SomeUrl"
   dataType: "json",
   contentType: "application/json; charset=utf-8",
   data: ? });

is there any example to post multiple objects to a controller. How the data for the ajax post have to look like ?

[HttpPost]
public string Register(UserLogin userLogin, Contact contact)
{
}

UserLogin

public class UserLogin 
{
   public string Username { get; set; }
   public string Password { get; set; }
}

Contact

public class Contact
{
   public string Firstname { get; set; }
   public string Lastname { get; set; }
}

AJAX ?

$.ajax({
   type: "POST",
   url: "SomeUrl"
   dataType: "json",
   contentType: "application/json; charset=utf-8",
   data: ? });
Share Improve this question asked Jul 5, 2013 at 7:12 MR.ABCMR.ABC 4,86213 gold badges47 silver badges89 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 5

Try this

$.ajax({
   type: "POST",
   url: "SomeUrl"
   dataType: "json",
   contentType: "application/json; charset=utf-8",
   data: {
       'userLogin' : {
           'Username' : 'Username',
           'Password' : 'Password'
       },
       'contact' : {
           'Firstname' : 'Firstname',
           'Lastname' : 'Lastname'
       }
   }
});

Just need to change javascript. Pass your object like this after creating

var loginObject = {
  Username: uname,//get it using jQuery $('#Username').val()
  Password : pswrd    //same way
};
var contact = {
  Firstname = "",
  Lastname = "",
};

And in ajax call,

data: {userLogin: loginObject, contact: contactObject}

You can follow the below snippet

var userLogin = {
UserName : "", Password : ""
};

var contact = {
FirstName : "", LastName : ""
};

Then you can assin the data to the ajax call like data : {userLogin : userLogin, contact : contact}

发布评论

评论列表(0)

  1. 暂无评论