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 :
- public async Task
CreateUser([FromBody] UserViewModel viewmodel) - {
- try
- {
- ...
- }
Startup.cs - Adding services.AddRazorPages().AddNewtonsoftJson();
- public void ConfigureServices(IServiceCollection services)
- {
- services.AddControllersWithViews();
- // services.AddMvc();
- services.AddControllers();
- //.AddNewtonsoftJson(options =>
- //{
- // options.SerializerSettings.ContractResolver = new DefaultContractResolver();
- //});
- services.AddRazorPages().AddNewtonsoftJson();
- }
ajax call
- var viewModel = {
- UserName: $('#UserName').val(),
- Password: $('#Password').val(),
- FirstName : $('#FirstName').val(),
- SurName: $('#SurName').val(),
- PhoneNumber: $('#PhoneNuber').val(),
- VirtualNumber: $('#VirtualNumber').val(),
- IsActive: true,
- EmailAddress : $('#EmailAddress').val()
- }
- //url = "/Users/CreateUser";
- //$.post(url, { UserViewModel: JSON.stringify(viewModel) })
- // .done(function (response, status, jqxhr) {
- // alert("ass");
- // })
- // .fail(function (jqxhr, status, error) {
- // })
- $.ajax({
- type: "POST",
- contentType: "application/json",
- data: JSON.stringify(viewModel),
- url: "/Users/CreateUser",
- success: function (data) {
- //return callback(data);
- },
- error: function (error, statusText) {
- // return callback(error);
- }
- });
Model
- public class UserViewModel
- {
- public Guid UserID { get; set; }
- ///
- /// Db Id - Unique. To be used by for all calls.
- ///
- public int ID { get; set; }
- public string UserName { get; set; }
- public string Password { get; set; }
- public string FirstName { get; set; }
- public string SurName { get; set; }
- public string PhoneNumber { get; set; }
- public string VirtualNumber { get; set; }
- public bool IsActive { get; set; }
- public bool EmailAddress { get; set; }
- }
Please help me out in identifying what am i missing.
Regards,
Kiran
Sachin SinghPosted Dec 23, 2020, 5:09 AM
kiran aPosted Dec 23, 2020, 4:59 AM
Sachin SinghPosted Dec 23, 2020, 3:23 AM