删除视图将null对象返回给控制器

时间:2015-09-23 10:01:48

标签: asp.net-mvc

我是ASP.NET MVC的新手,我正在尝试开发一个简单的应用程序来实现CRUD操作,但是当回到控制器时,Delete操作有一个奇怪的问题,因为它返回一个null对象,不允许操作完成。我将在下面显示模型,控制器及其各自视图的代码。

型号:

public class Biblioteca
{
    public int IdBiblioteca { get; set; }
    public string Nome { get; set; }
    public string Endereco { get; set; }
}

控制器

public class BibliotecaController : Controller
{
    ADAO dao = DAOFactory.GetInstance(DAOFactory.DAOType.Biblioteca);

    [HttpGet]
    public ActionResult DeleteLibrary(int id)
    {
        return View(dao.Select(id));
    }

    [HttpPost]
    public ActionResult DeleteLibrary(Biblioteca b)
    {
        dao.Delete(b);
        return RedirectToAction("Index");
    }
}

查看DeleteLibrary

@model BibliotecaWebApp.Models.Biblioteca

<h2>DeleteLibrary</h2>
<h3>Are you sure you want to delete this?</h3>
<div>
    <h4>Biblioteca</h4>
    <hr />
    <dl class="dl-horizontal">
        <dt>@Html.DisplayNameFor(model => model.IdBiblioteca)</dt>
        <dd>@Html.DisplayFor(model => model.IdBiblioteca)</dd>
        <dt>@Html.DisplayNameFor(model => model.Nome)</dt>
        <dd>@Html.DisplayFor(model => model.Nome)</dd>
        <dt>@Html.DisplayNameFor(model => model.Endereco)</dt>
        <dd>@Html.DisplayFor(model => model.Endereco)</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>

正如我们在控制器片段中看到的,每个操作都有两个控制器:[HttpGet]检索要在确认视图中显示的数据,然后才能删除[HttpPost]。一旦从视图中获取null Biblioteca对象以执行排除,[HttpPost] DeleteLibrary就会出现问题。下面有两个截图,可以更好地呈现这一点:

[HttpGet] DeleteLibrary正常工作:

enter image description here

但是当用户点击Delete按钮时,在[HttpPost] DeleteLibrary方法上会收到一个null对象,如下所示:

enter image description here

我的问题是:为什么返回的对象在传递给视图时会变为空?可能是什么问题?

1 个答案:

答案 0 :(得分:0)

使用此

&#13;
&#13;
**@using (Html.BeginForm()) {
        @Html.AntiForgeryToken()
        @Html.HiddenFor(m => m.IdBiblioteca)
        <div class="form-actions no-color">
            <input type="submit" value="Delete" class="btn btn-default" /> |
            @Html.ActionLink("Back to List", "Index")
        </div>
    }**
&#13;
&#13;
&#13;

而不是

&#13;
&#13;
**@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>
    }**
&#13;
&#13;
&#13;