locked
Trying to update a Database record RRS feed

  • Question

  • User1750806012 posted

    I am not sure what i am doing wrong,
    I am trying to update a single record with a API with javascript.

    [HttpPut("{id}")]
    		public async Task<IActionResult> UpdateProduct(int id, Product product)
    		{
    			if (id != product.id)
    				return BadRequest();
    
    			var editproduct = await _context.products.FindAsync(id);
    
    			if (editproduct == null)
    		        return NotFound();
    
    			_context.Update(product);
    // I also tried this _context.Entry(product).State = EntityState.Modified; await _context.SaveChangesAsync(); return NoContent(); }

    javascript:

    function EditProduct(id) {
        const itemid = document.getElementById("Idhidden").value;
        const item = {
            id : parseInt(itemid, 10),
            title : document.getElementById("TitleFIeld").value,
            price : document.getElementById("PriceFIeld").value,
            quantity : document.getElementById("QuantityInput").value
        }
        fetch(`${url}/${id}`, {
            method: 'PUT',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(item)
        })
            .then(() => GetProducts())
            .catch(error => console.log('unable to edit.', error));
    }

    I get no errors in the console log

    I got it to work like this.
    but sometimes it works but sometimes it doesnt

    			if (editproduct != null)
    			{
    
    				editproduct.Title = product.Title;
    				editproduct.Price = product.Price;
    				editproduct.Quantity = product.Quantity;
    				await _context.SaveChangesAsync();
    
    				return NoContent();
    			}

    And I dont think this would be the best way to achive it especially if you have allot more fields


    Friday, May 14, 2021 7:01 PM

Answers

All replies

  • User475983607 posted

    You're working with a disconnected entity.  I assume the hidden field value is not what you expect.

    Friday, May 14, 2021 7:38 PM
  • User1750806012 posted

    The "Idhidden" is working well. I have also tried to pass in a existing id number like this as well:

     const item = {
            id : 19,
            title :  "jack",
            price :  100,
            quantity : 10
        }

    it reacted the same way,
    after clicking 5 times it finally adjusted that record with id 19
    so it does work but not efficient at all.

    I think the problem is in C# but I dont know what it would be 

    Friday, May 14, 2021 7:46 PM
  • User475983607 posted

    osyris

    it reacted the same way,
    after clicking 5 times it finally adjusted that record with id 19
    so it does work but not efficient at all.

    I think the problem is in C# but I dont know what it would be 

    Seriously?  The C# code is self-writing?  The most likely issue is a logical bug in you code.  Do some basic troubleshooting.  Set a break point and verify the data.  Use dev tools to see what's submitted to the server. 

    Friday, May 14, 2021 7:53 PM
  • User1750806012 posted

    I have tested it now a couple of times 
    everytime 2 times when I try to adjust it fails
    only at the 3 time it works
    and than all records work perfectly

    its really strange I have no clue what it is

    Friday, May 14, 2021 7:53 PM
  • User475983607 posted

    osyris

    I have tested it now a couple of times 
    everytime 2 times when I try to adjust it fails
    only at the 3 time it works
    and than all records work perfectly

    its really strange I have no clue what it is

    I get the feeling you are not debugging the code.  You've defined itemid as a const which makes the variable read only.   Is this the design intention?  Seems rather odd to me but...???

    const itemid = document.getElementById("Idhidden").value;

    What about the "id" function parameter which is used to create the route parameter?  Seems "id" can be different than itemid.  

    Friday, May 14, 2021 8:28 PM
  • User1750806012 posted

    Im sorry my last reply was about 10 seconds after your reply I did not read it.
    I have looked into the javascript code and I have coded things different to figure out what was going on
    The problem was a slide feature that apparently faded-out to quickly  before the post function could read the inputs.

    I still have the question what would be the best way to save a record in asp net core.
    given the same example without the javascript part offcourse

    Friday, May 14, 2021 10:31 PM
  • User753101303 posted

    Hi,

    catch is only for network errors. I would start by checking https://developer.mozilla.org/en-US/docs/Web/API/Response/ok to make sure if thre http status code is 2xx.

    Could it be that you are a situation in which you return a BadRequest until you navigate on the correct url ???

    Saturday, May 15, 2021 9:33 AM
  • User475983607 posted

    Im sorry my last reply was about 10 seconds after your reply I did not read it.
    I have looked into the javascript code and I have coded things different to figure out what was going on
    The problem was a slide feature that apparently faded-out to quickly  before the post function could read the inputs.

    I still have the question what would be the best way to save a record in asp net core.
    given the same example without the javascript part offcourse

    Below is the pattern for disconnected entities.

        context.Update(entity);
        context.SaveChanges();

    Reference documentation.

    https://docs.microsoft.com/en-us/ef/core/saving/disconnected-entities

    The programming pattern for PUT can be found in the official docs or any beginning level Web API tutorial.

    https://docs.microsoft.com/en-us/aspnet/core/tutorials/first-web-api?view=aspnetcore-5.0&tabs=visual-studio

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Saturday, May 15, 2021 10:32 AM