Saturday, October 1, 2022

Call Web API Post method from Jquery

 $(document).ready(function () {

            $(".btn_click").click(function () {


                var FullName = $("#FullName").val();

                var Mobile_Number = $("#Mobile_Number").val();

                var Email = $("#Email").val();

                var Investment_Amount = $("#Investment_Amount").val();

                var Country = $('[id$=Country] option:selected').val();

                var STO_ID = $("input[name='sto']:checked").map(function () {

                    return this.value;

                }).get().join(',');


                ;

                var UserRegister = new Object();


                UserRegister.FullName = FullName;

                UserRegister.Mobile_Number = Mobile_Number;

                UserRegister.Email = Email;

                UserRegister.Investment_Amount = Investment_Amount;

                UserRegister.Country = Country;

                UserRegister.STO_ID = STO_ID;


                $.ajax({

                    url: 'https://localhost:44334/api/Register',

                    type: 'POST',

                    dataType: 'json',

                    contentType: 'application/json; charset=utf-8',

                    data: JSON.stringify(UserRegister),

                    success: function (data, textStatus, xhr) {

                        console.log(data);

                    },

                    error: function (xhr, textStatus, errorThrown) {

                        console.log('Error in Operation');

                    }

                });


            });

        });



C#




Make a class with all that fields



Add this CORS line in the following order in Startup file


    public void ConfigureServices(IServiceCollection services)

        {

          

            string URL= Convert.ToString(Configuration["URLConfig:RegisterZcrypto"]);


            services.AddCors(options =>

            {

                options.AddPolicy("CorsPolicy",

                    builder => builder.WithOrigins(URL)

                    .AllowAnyMethod()

                    .AllowAnyHeader());

                //.AllowCredentials());

            });

            services.AddControllers();

        }


       public void Configure(IApplicationBuilder app, IWebHostEnvironment env)

        {

            if (env.IsDevelopment())

            {

                app.UseDeveloperExceptionPage();

            }


            app.UseHttpsRedirection();


            app.UseRouting();

            app.UseCors("CorsPolicy");

            app.UseAuthorization();


            app.UseEndpoints(endpoints =>

            {

                endpoints.MapControllers();

                endpoints.MapGet("/", async context =>

                {

                    await context.Response.WriteAsync("Welcome to running ASP.NET Core on AWS Lambda");

                });

            });


          

        }