kiran a

kiran a

  • NA
  • 20
  • 9.3k

Model is not getting bind from Ajax Call - .Net core 3.1

Dec 22 2020 7:19 PM
Hi Team,
 
I am working on web application .Net core 3.1 .
 
after ajax call . model returned is always null .
 
Please help to get issue resolved. I have tried all options including adding [FromBody] in controller.
 
and in startup adding "services.AddRazorPages().AddNewtonsoftJson();"
 
But still not able to resolve issue.
 
Below is code snippet.
 
Controller :
  1. public async Task<IActionResult> CreateUser([FromBody] UserViewModel viewmodel)  
  2. {  
  3. try  
  4. {  
  5. ...  
  6. }  
Startup.cs - Adding services.AddRazorPages().AddNewtonsoftJson();
  1. public void ConfigureServices(IServiceCollection services)  
  2. {  
  3. services.AddControllersWithViews();  
  4. // services.AddMvc();  
  5. services.AddControllers();  
  6. //.AddNewtonsoftJson(options =>  
  7. //{  
  8. // options.SerializerSettings.ContractResolver = new DefaultContractResolver();  
  9. //});  
  10. services.AddRazorPages().AddNewtonsoftJson();  
  11. }  
ajax call
  1. var viewModel = {  
  2. UserName: $('#UserName').val(),  
  3. Password: $('#Password').val(),  
  4. FirstName : $('#FirstName').val(),  
  5. SurName: $('#SurName').val(),  
  6. PhoneNumber: $('#PhoneNuber').val(),  
  7. VirtualNumber: $('#VirtualNumber').val(),  
  8. IsActive: true,  
  9. EmailAddress : $('#EmailAddress').val()  
  10. }  
  11. //url = "/Users/CreateUser";  
  12. //$.post(url, { UserViewModel: JSON.stringify(viewModel) })  
  13. // .done(function (response, status, jqxhr) {  
  14. // alert("ass");  
  15. // })  
  16. // .fail(function (jqxhr, status, error) {  
  17. // })  
  18. $.ajax({  
  19. type: "POST",  
  20. contentType: "application/json",  
  21. data: JSON.stringify(viewModel),  
  22. url: "/Users/CreateUser",  
  23. success: function (data) {  
  24. //return callback(data);  
  25. },  
  26. error: function (error, statusText) {  
  27. // return callback(error);  
  28. }  
  29. });  
Model
  1. public class UserViewModel  
  2. {  
  3. public Guid UserID { getset; }  
  4. /// <summary>  
  5. /// Db Id - Unique. To be used by for all calls.  
  6. /// </summary>  
  7. public int ID { getset; }  
  8. public string UserName { getset; }  
  9. public string Password { getset; }  
  10. public string FirstName { getset; }  
  11. public string SurName { getset; }  
  12. public string PhoneNumber { getset; }  
  13. public string VirtualNumber { getset; }  
  14. public bool IsActive { getset; }  
  15. public bool EmailAddress { getset; }  
  16. }  
Please help me out in identifying what am i missing.
 
Regards,
Kiran

Answers (3)