Hey, I am making put request using vue.js and axios to my controller but it is passing null to controller

71 Views Asked by At

request object is null in my controller action methodAs, mentioned before I am making put request using vue.js and axios to my asp.net core controller at backend for updating product but it is passing null to my controller's UpdateProduct action method.

I am getting updated product in request payload but it is null in my controller action method. Here is my request payload:

{id: 19, name: "New It", description: "Product Description", value: "Rs.1.99"}
description
: 
"Product Description"
id
: 
19
name
: 
"New It"
value
: 
"Rs.1.99"

here is my vue.js code for updating product:

updateProduct() {
    this.loading = true;
    axios.put('/Admin/products', this.productModel)
        .then(res => {
            console.log(res.data);
            this.products.splice(this.objectIndex, 1, res.data);
        })
        .catch(err => { console.log(err); })
        .then(() => {
            this.loading = false;
        });
}

here is my Index.cshtml code:

@page
@model Shop.Ui.Pages.Admin.IndexModel
@{
}
@section scripts
    {
    <script src="https://unpkg.com/[email protected]/dist/vue.js"></script>

    <script src="https://unpkg.com/[email protected]/dist/axios.min.js"></script>
    <script src="~/js/admin/main.js"></script>

}
<div id="app">
 <button v-on:click="getProducts">Get Products</button>
    <div>
        <p v-for="(product,index) in products">
            {{product.id}} - {{product.name}} - {{product.description}}
            <a @@click="editProduct(product,index)">Edit</a>
            <a @@click="deleteProduct(product.id)">Remove</a>
        </p>
    </div>
    
    <div>
        
        <input v-model="productModel.name"/> 
        <input v-model="productModel.description" />
        <input v-model.number="productModel.value" />
        <button @@click="createProduct" v-if="!productModel.id">Create Product</button>
        <button @@click="updateProduct" v-else>Update Product</button>
        
    </div>
</div>

My controller action method for updating product here, null is being passed to my request object.


        [HttpPut("products")]
        public async Task<IActionResult> UpdateProduct([FromBody] UpdateProduct.Request request) => Ok(await new UpdateProduct(_ctx).Do(request));

Here is my defination for UpdateProduct:

 public class UpdateProduct
    {
        private ApplicationDbContext _context;

        public UpdateProduct(ApplicationDbContext context)
        {
            _context = context;
        }
        
        
        public async Task<Response> Do(Request request)
        {
            try
            {
                var product = _context.Products.Where(x => x.Id == request.Id).FirstOrDefault();

                product.Name = request.Name;
                product.Description = request.Description;
                product.Value = request.Value;

                await _context.SaveChangesAsync();
                return new Response
                {
                    Id = product.Id,
                    Name = product.Name,
                    Description = product.Description,
                    Value = product.Value
                };
            }
            catch (Exception ex)
            {
                // Handle the exception here, you can log it or throw a custom exception.
                // For example, you can log the exception and then throw a custom exception.
                // Logging should be done using a proper logging library like Serilog or NLog.

                // Log the exception
                Console.WriteLine($"An error occurred: {ex.Message}");

                // You can re-throw a custom exception if needed.
                throw new ApplicationException("An error occurred while updating the product.");
            }
        }



        [Serializable]
        public class Request
        {
            public int Id {  get; set; }
            public string Name { get; set; }
            public string Description { get; set; }
            public decimal Value { get; set; }
        }
        [Serializable]
        public class Response
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public string Description { get; set; }
            public decimal Value { get; set; }

        }
    }
}

Here is my code for program.cs:

// Add services to the container.
builder.Services.AddRazorPages();
builder.Services.AddDbContext<ApplicationDbContext>(options => { options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"));
    options.EnableSensitiveDataLogging(); }) ; 
builder.Services.AddControllersWithViews().AddNewtonsoftJson(options =>
    options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
);
builder.Services.AddCors(options =>
{
    options.AddPolicy( "MyCorsPolicy",
                      builder =>
                      {
                          builder.AllowAnyOrigin()
                          .AllowAnyMethod()
                          .AllowAnyHeader();
                      });
});
var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    
    app.UseExceptionHandler("/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();


app.UseRouting();
app.MapDefaultControllerRoute();
app.UseCors("MyCorsPolicy");

app.UseAuthorization();


app.MapRazorPages();

app.Run();

Please can anyone suggest me to resolve this error.

0

There are 0 best solutions below