question

osyris-3187 avatar image
0 Votes"
osyris-3187 asked osyris-3187 answered

Ap put request

I dont know what is going on on this website.
But everytime i try to place a question here i get "Acces denied" Message on this website.

its very annoying please fix it.

dotnet-aspnet-generaldotnet-aspnet-core-mvc
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

osyris-3187 avatar image
0 Votes"
osyris-3187 answered

My actual question:

I am trying to create a PUT request system i have work on it for a couple of hours to make it work but it has been a complete drama, sometimes the code work and Allot of times it completly fails. I feel like this could be code way better and more efficient especially from the client side
the idea is that it should only update the fields that are not empty.


C#:

 [HttpPut("{id}")]
             public async Task<IActionResult> EditProduct(int id, ProductDto dto)
             {
                 var find = await _dbContext.Products.FindAsync(id);
        
                 if (find == null)
                     return BadRequest("Could not find product");
                    
                 if(dto.File != null)
                 {
                     if (dto.File.Length > 0)
                     {
        
                         string root = _env.WebRootPath + "/client/src/images/ProductImages/";
                         string oldFileName = find.ImagePath;
        
                         if (System.IO.File.Exists(Path.Combine(root, oldFileName)))
                             System.IO.File.Delete(Path.Combine(root, oldFileName));
        
        
                         string filename = Guid.NewGuid().ToString() + "_" + dto.File.FileName;
                         string filepath = Path.Combine(root, filename);
        
                         using (var stream = System.IO.File.Create(filepath))
                         {
                             await dto.File.CopyToAsync(stream);
                         }
        
                         find.ImagePath = filename;
                     }
                 }
                 if(!string.IsNullOrWhiteSpace(dto.Name)){ find.Name = dto.Name; }
                 if(!string.IsNullOrWhiteSpace(dto.Description)){ find.Description = dto.Description; }
                 if(dto.Price >= 0){ find.Price = dto.Price; }
                 if (!string.IsNullOrWhiteSpace(dto.Category)) { find.Category = dto.Category; }
        
                 await _dbContext.SaveChangesAsync();
        
                 return Ok();
             }
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

osyris-3187 avatar image
0 Votes"
osyris-3187 answered AgaveJoe edited

Client side Reactjs :

 const edit = async () =>{
         const[status,setStatus] = useState("");
         const[name,setName] = useState(null);
         const[description,setDescription]= useState(null);
         const[price,setPrice] = useState(null);
         const[category,setCategory] = useState(null);
         const[file, setFile] = useState(null);
         const inputRef2 = useRef(null);
        
     const edit = async () =>{
         const formdata = new FormData();
            
     let senddata = formdata
        
         if(file !== null){ formdata.append("file",file, file.name);  }
         if(name === null){formdata.append("name", " ");}
         if(description === null){formdata.append('description'," ");}
         if(price === null){formdata.append('price'," ");}
         if(category === null){formdata.append('category'," ");}
        
     let object = {
         name: name,
         description : description,
         price: price,
         category: category,
         file: null
     }
        
     if(name === null){ object.name = " ";}
     if(description === null){ object.description = " ";}
     if(price === null){ object.price = -1;}
     if(category === null){ object.category = " ";}
        
       if(file === null){  senddata = object; }
        
       console.log(senddata)
        
       const res = await  axios.put(url,senddata)
         if(res.status === 200) {
             setStatus("Product has been succesfuly updated") }
         else{
             setStatus("Product has Failed to update")  }
· 3
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

As far as I can tell, "file" is initialized to null and never set to an actual value. Can you explain the general design intent?

0 Votes 0 ·

Offcourse

125693-edit.png




as you can see on the image only when i fil in a field it should update the rest should remain the same.
and if you would only upload a Image it should only update a image.
i have put so much code in it, i think this can be coded much and much better.
I have tried to ask on Javascript forums but it seems to be to complicated for them.
Hopefully someone can help me here.

0 Votes 0 ·
edit.png (48.0 KiB)

i have put so much code in it, i think this can be coded much and much better. I have tried to ask on Javascript forums but it seems to be to complicated for them.

For the second time, the "file" state is initialized to null and "file" is never assigned a different value yet you use "file" in conditional logic.

The "name" property has a similar and confusing logic. Name is initialized to null. The logic immediately checks if "name" is null, which is it because the code specifically set "name" to null. As far as I can tell, "name" is always null. Also formdata and object always have an empty "name" values.

I would expect the "name" value to come from the user input but there is no place in the code where user inputs are referenced. My best guess is you copied and pasted React code blocks without understanding what the code does. Most likely you assume a certain functionality while the rest of see what the code actually does.

What is the requirement? Update the image name, price, description, etc???










0 Votes 0 ·
Bruce-SqlWork avatar image
1 Vote"
Bruce-SqlWork answered Bruce-SqlWork edited

this is pretty poorly written, no wonder you have trouble.

You should either post json, or do a form post, not both. the server put method does not support form posts, so if a file is included it will not work.

also, why a single space for nulls?

assuming the hook values are bound to form elements they would all be string, but your code uses them as others data types.

your code sets a space to for null numbers, but the server gets a binding error when this happens, as a space can not map to a number.

it looks like you are using an entity for a form post. bad design.

it looks like edit is react component, but components should not be async. the async calls should be in a useEffect() callback.






5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

osyris-3187 avatar image
0 Votes"
osyris-3187 answered

This was not the full code , every time i post the full script i get a error on this website.
also I have not finished the design

I am trying to upload the Code to that part but im not even allowed:


     **Access Denied

You don't have permission to access "http://docs.microsoft.com/answers/answers/524392/post.html" on this server.
Reference #18.b5361602.1629747933.2f50a30a**




5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

osyris-3187 avatar image
0 Votes"
osyris-3187 answered

Only way i can show the rest of the code:

125727-code.png



code.png (35.9 KiB)
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.