Search code examples
asp.netasp.net-mvcrazorhtml-helper

DisplayFor helper does not populate records from database in delete view


i want to delete a record from my database , but in the delete confirm view

the DisplayFor Helper Does Not Show any record from my database

DisplayNameFor does work correctly , i don't know what i'm doing wrong,

any help would be appreciated.

here is my code.

Controller Code :

public ActionResult Delete(int id)
    {

        return View();
    }

    [HttpPost]
    public ActionResult Delete(int id, FormCollection collection)
    {
        try
        {
            using (var db = new Database1Entities())
            {

                var tooltip = db.tooltip_tbl.Find(id);
                db.tooltip_tbl.Remove(tooltip);
                db.SaveChanges();

                return RedirectToAction("Index");
            }

        }
        catch
        {
            return View();
        }
    }

the view code :

@model WebApplication7.Models.tooltip_tbl

@{
ViewBag.Title = "Delete";
}

<h2>Delete</h2>

<h3>Are you sure you want to delete this?</h3>

<div>
<hr />
<dl class="dl-horizontal">
    <dt>@Html.DisplayNameFor(item => item.Title)</dt>

    <dd>@Html.DisplayFor(item => item.Title)</dd>

    <dt>@Html.DisplayNameFor(item => item.Info)</dt>

    <dd>@Html.DisplayFor(item => item.Info)</dd>

</dl>

@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>
}
</div>

Solution

  • With your current code, your GET action method is not passing anything to your delete view. So the Model of your view is actually null and the DisplayFor helper method is graciously doing the null check for you , hence you are not getting any null reference exception.

    You need to pass a valid tootip object to your view, in your GET action.

    public ActionResult Delete(int id)
    {
        var tooltip = db.tooltip_tbl.Find(id);
        return View(tooltip);
    }