How to delete row from db table with 2 primary keys

I'm new using MVC C# on web applications...and I am having troubles deleting a row in the database...the result is an "HTTP Error 400.0 - Bad Request"

I'm not get this error when tables have just 1 primary keys.

Controller:

// GET: DocenteCursoes/Delete/5
    public ActionResult Delete(string curso, string docente)
    {
        if (curso == null && docente == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        DocenteCurso docenteCurso = db.DocenteCurso.Find(curso, docente);
        if (docenteCurso == null)
        {
            return HttpNotFound();
        }
        return View(docenteCurso);
    }

    // POST: DocenteCursoes/Delete/5
    [HttpPost, ActionName("Delete")]
    [ValidateAntiForgeryToken]
    public ActionResult DeleteConfirmed(string curso, string docente)
    {
        DocenteCurso docenteCurso = db.DocenteCurso.Find(curso, docente);
        db.DocenteCurso.Remove(docenteCurso);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            db.Dispose();
        }
        base.Dispose(disposing);
    }

Model:

[Table("DocenteCurso")]
public partial class DocenteCurso
{
    [Key]
    [Column(Order = 0)]
    [StringLength(50)]
    public string Curso { get; set; }

    [Key]
    [Column(Order = 1)]
    [StringLength(50)]
    public string Docente { get; set; }
}

View:

@using (Html.BeginForm()) {
    @Html.AntiForgeryToken()

    <div class="form-actions no-color">
        <input type="submit" value="Delete" class="btn btn-default" /> |
        @Html.ActionLink("Back to List", "Index")
    </div>
}

2 answers

  • answered 2018-03-13 20:28 koryakinp

    Most probably you are getting BadRequest due to this condition:

    if (curso == null && docente == null)
    {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }
    

    Which has nothing to do with whatever or not your entity has a composite primary key. Make sure you are calling a correct controller action.

    Note that Html.BeginForm() with no parameters, sends an HTTP POST to the current URL.

  • answered 2018-03-13 20:28 Erlangga Hasto Handoko

    Ok, let's start with a well-constructed URL like this :

    http://yourserver/DocenteCursoes/Delete?curso=firstparam&docente=secondparam
    

    Try that in an Internet browser first, and tell me if you could get rid of the 404 error.