Home Issue with Delete Action returning HttpNotFound MVC
Reply: 2

Issue with Delete Action returning HttpNotFound MVC

Man Down
1#
Man Down Published in 2017-12-07 13:35:58Z

i have list of user Emails and than i try to make delete method , but i didnt understand why it just returning HttpNotFound , did i miss something!Can anyone direct me in the right direction? thx

Controller:

public ActionResult Delete(string User) 
{

    var db = new DataContext();
    var u = db.PX.Find(User);
    if (u==null)
    {
        return HttpNotFound();
    }
    return View(u);

}
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(string User)
{
    var db = new DataContext();
    var u = db.PX.Find(User);
    db.PX.Remove(u);
    db.SaveChanges();
    return RedirectToAction("Index");
}

View - Index:

<table>
    <thead>
        <tr>
            <th>Email</th>
        </tr>
    </thead>
    <tbody>
        @foreach (var user in Model)
        {
            <tr>
                <td>

                     <a href="/User/Delete?User=@user.Email">delete</a>
                </td>
            </tr>
        }
    </tbody>
</table>

Class :

public class user
{
    public string Email { get; set; }
    private string password = "";

    } }
}
objectively C
2#
objectively C Reply to 2017-12-07 14:26:34Z

Consider updating your controller to the following, which simplifies the query to the PX table and ensures that you grab the appropriate value:

public ActionResult Delete(string User) 
{

    var db = new DataContext();
    var u = db.PX.Where(x=> x.Email == User).FirstOrDefault();  //This line updated
    db.PX.Remove(u);
    db.SaveChanges();
    return RedirectToAction("Index");

}

EDIT to reflect comment

In your Delete(string User) method, you are trying to return the Delete view, but really you want to reroute to the Index view.

Georg Patscheider
3#
Georg Patscheider Reply to 2017-12-07 14:14:39Z

DbSet.Find takes the primary key of the entity (usually a long or Guid). If no entity with this primary key is found, it returns null.

If the user email is not the primary key in the DB, look up the user with SingleOrDefault instead. SingleOrDefault will throw an exception if more than one record matches the given criteria (we want this because the Email is used to identify users uniquely). If no matching record is found, it returns null.

var u = db.PX.SingleOrDefault(u => u.Email == User);
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.313199 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO