简体   繁体   中英

Angular - 400 Error (Bad Request) when using PUT

In my Angular program, I'm trying to post a row that's entered by the user from my table to my database. But, whenever I use put, in the console, I'm getting an error that's saying

PUT 400 (Bad Request)

and the response that I'm getting from the server is

{"Message":"The request is invalid.","MessageDetail":"The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'System.Web.Http.IHttpActionResult PutPTOData(Int32, PTOTracker.Models.PTOData)' in 'PTOTracker.Controllers.PTODataController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter."}

It's saying that I'm not entering an ID but I thought I was.

Here's my model:

namespace PTOTracker.Models
{
public class PTOData
{
[Key]
public int ID { get; set; }
public int EmpKey { get; set; }
public string type { get; set; }
public DateTime date { get; set; }
public string fullhalf { get; set; }
public int hours { get; set; }
public string scheduled { get; set; }
public string notes { get; set; }
public bool inPR { get; set; }
public DateTime? prDate { get; set; }

} }

here's my save function from my component:

    saveNewRow(): void {
    this.ptoDataService.save(this.newRow)
        .then(PTOData => {
            this.ptoData.push({
                ID: 123456,
                EmpKey: this.empInfo[this.selectedEmployee].EmpKey,
                type: this.selectedType,
                date: this.newRow.date,
                fullhalf: this.newRow.fullhalf,
                hours: this.newRow.hours,
                scheduled: this.newRow.scheduled,
                notes: this.newRow.notes,
                inPR: (this.newRow.inPR ? true : false),
                prDate: this.newRow.prDate
            })
        })

   }

and here's my save function in my service:

    save(pto: PTOData): Promise<PTOData> {
    return this.http
        .put(this.ptoDateUrl + '/' + pto.ID, pto, this.options)
        .toPromise()
        .then(res => res.json().data as PTOData)
        .catch(this.handleError);
}

Here's my PTODataController:

 using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Data.Entity.Infrastructure; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using System.Web.Http.Description; using PTOTracker.Models; namespace PTOTracker.Controllers { public class PTODataController : ApiController { private PTOTrackerContext db = new PTOTrackerContext(); // GET: api/PTOData public IQueryable<PTOData> GetPTODatas() { return db.PTODatas; } // GET: api/PTOData/5 [ResponseType(typeof(PTOData))] public IHttpActionResult GetPTOData(int id) { PTOData pTOData = db.PTODatas.Find(id); if (pTOData == null) { return NotFound(); } return Ok(pTOData); } // PUT: api/PTOData/5 [HttpPut] [ResponseType(typeof(void))] [Route("api/PTOData/{id}")] public IHttpActionResult PutPTOData(int id, PTOData pTOData) { if (!ModelState.IsValid) { return BadRequest(ModelState); } if (id != pTOData.ID) { return BadRequest(); } db.Entry(pTOData).State = EntityState.Modified; try { db.SaveChanges(); } catch (DbUpdateConcurrencyException) { if (!PTODataExists(id)) { return NotFound(); } else { throw; } } return StatusCode(HttpStatusCode.NoContent); } // POST: api/PTOData [ResponseType(typeof(PTOData))] public IHttpActionResult PostPTOData(PTOData pTOData) { if (!ModelState.IsValid) { return BadRequest(ModelState); } db.PTODatas.Add(pTOData); db.SaveChanges(); return CreatedAtRoute("DefaultApi", new { id = pTOData.ID }, pTOData); } // DELETE: api/PTOData/5 [ResponseType(typeof(PTOData))] public IHttpActionResult DeletePTOData(int id) { PTOData pTOData = db.PTODatas.Find(id); if (pTOData == null) { return NotFound(); } db.PTODatas.Remove(pTOData); db.SaveChanges(); return Ok(pTOData); } protected override void Dispose(bool disposing) { if (disposing) { db.Dispose(); } base.Dispose(disposing); } private bool PTODataExists(int id) { return db.PTODatas.Count(e => e.ID == id) > 0; } } } 

The issue seems to be this:

saveNewRow(): void {
this.ptoDataService.save(this.newRow)
    .then(PTOData => {
        this.ptoData.push({
            ID: 123456,
            EmpKey: this.empInfo[this.selectedEmployee].EmpKey,
            type: this.selectedType,
            date: this.newRow.date,
            fullhalf: this.newRow.fullhalf,
            hours: this.newRow.hours,
            scheduled: this.newRow.scheduled,
            notes: this.newRow.notes,
            inPR: (this.newRow.inPR ? true : false),
            prDate: this.newRow.prDate
        })
    })

}

You are pushing your new object after you made the request, not before. Should be something like this:

this.ptoDataService.save({
                ID: 123456,
                EmpKey: this.empInfo[this.selectedEmployee].EmpKey,
                type: this.selectedType,
                date: this.newRow.date,
                fullhalf: this.newRow.fullhalf,
                hours: this.newRow.hours,
                scheduled: this.newRow.scheduled,
                notes: this.newRow.notes,
                inPR: (this.newRow.inPR ? true : false),
                prDate: this.newRow.prDate})
    .then((response: any) => { //do what you want with the response.})

Your code to add the record to the database is not correct.

Firstly, change the JS side of things as per camaron's solution.

Then on the server side, you need to add your entity to the database. https://stackoverflow.com/a/22222636/34092 has a great sample.

db.Entry(pTOData).State = EntityState.Modified;

needs to be changed to:

db.PTODatas.Add(pTOData);

and:

return StatusCode(HttpStatusCode.NoContent);

needs to be changed to:

return Ok(pTOData);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM