Reputation: 4862
I've a controller with a post action (multiple parameters). Using javascript ajax to post the data, i got a 500 Internal Server Error
. Any suggestion ?
Routing
config.Routes.MapHttpRoute(
null,
routeTemplate: "api/{controller}/{action}"
);
Ajax
public register(data: any): bool {
var url = this.baseUrl + "Account/Register/";
var xhr: JQueryXHR = $.ajax({
type: "POST",
url: url,
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({
login: ({ Id: 0, "Username": "myUser", "Password": "myPass" }),
company: ({ Id: 0, "Name": "myCompany" })
}),
async: false,
cache: false,
});
return (xhr.status == 200);
}
Action
[HttpPost]
[AllowAnonymous]
[Mvc.ValidateAntiForgeryToken]
public void Register(UserLogin login, Company company)
UserLogin
public class UserLogin
{
public string Username { get; set; }
public string Password { get; set; }
}
Company
public class Company
{
public string Name { get; set; }
public string Street { get; set; }
...
}
Upvotes: 1
Views: 2514
Reputation: 4862
According to this link Posting parameters this is not possible. You can just pass one object to the action constructor while post.
Upvotes: 0
Reputation: 48982
I have not seen a syntax to declare javascript object like this. Maybe this could be the problem. Try:
data: JSON.stringify({
login: { UserId : 0, Username: "myUser", Password: "myPass" },
company: { CompanyId : 0, Name: "myCompany" }
})
Remove your (
and )
Another problem could be because of ValidateAntiForgeryToken
. This filter is to prevent CSRF, you have to send your Request Verification Token to the server. Try removing this filter first to see if it works.
Upvotes: 2
Reputation: 8020
try like this
public register(data: any): bool {
var url = this.baseUrl + "Account/Register/";
var xhr: JQueryXHR = $.ajax({
type: "POST",
url: url,
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({
login: ({ UserId : 0, Username: "myUser", Password: "myPass" }),
company: ({ CompanyId : 0, Name: "myCompany" })
}),
async: false,
cache: false,
});
return (xhr.status == 200);
}
UserLogin
public class UserLogin
{
public int UserId {get; set;}
public string Username { get; set; }
public string Password { get; set; }
}
Company
public class Company
{
public int CompanyId {get; set;}
public string Name { get; set; }
public string Street { get; set; }
...
}
Upvotes: 0