我正在尝试从视图中获取项目的 ID,以便我可以从数据库中删除它。这是我的模型
public class ModuleVM
{
public long Id { get; set; }
public string ModuleId { get; set; }
public string TypeName { get; set; }
[DataType(DataType.DateTime)]
public DateTime DateEntered { get; set; }
}
public class IndexModule
{
public List<ModuleVM> Modules { get; set; }
}
这是来自控制器的方法,它显示了表中的所有项目
public ActionResult ModuleList()
{
var modulesList = new IndexModule();
var modules = (from module in _db.Modules
orderby module.DateEntered
select new ModuleVM
{
Id = module.Id,
ModuleId = module.ModuleId,
TypeName = module.ModuleType.TypeName,
DateEntered = module.DateEntered
});
modulesList.Modules = modules.ToList();
return View(modulesList);
}
现在的观点
@using BootstrapSupport
@model AdminPortal.Areas.Hardware.Models.IndexModule
@{
ViewBag.Title = "Index";
Layout = "~/Views/shared/_BootstrapLayout.basic.cshtml";
}
<p>
@Html.ActionLink("Create New", "CreateModule", null, new {@class = "btn"})
</p>
<table class="table table-striped">
<caption></caption>
<thead>
<tr>
<th>ID</th>
<th>Module Id</th>
<th>Module type</th>
<th>Date Entered</th>
</tr>
</thead>
@foreach (var entry in Model.Modules)
{
<tr>
<td>@entry.Id</td>
<td>@entry.ModuleId</td>
<td>@entry.TypeName</td>
<td>@entry.DateEntered</td>
<td>
<div class="btn-group">
<a class="btn dropdown-toggle" data-toggle="dropdown" href="#">
Action<span class="caret"></span>
</a>
<ul class="dropdown-menu">
<li>@Html.ActionLink("Details", "Create")</li>
@if (Request.IsAuthenticated && HttpContext.Current.User.IsInRole("Admin"))
{
<li class="divider"></li>
<li>@Html.ActionLink("Edit", "Edit")</li>
<li>@Html.ActionLink("Delete", "DeleteModule","Module", new {Id = entry.Id})</li>//error probably here
}
</ul>
</div>
</td>
</tr>
}
</table>
现在是删除方法
public ActionResult DeleteModule(long Id)
{
// Mapper.CreateMap<Sorama.DataModel.SIS.ModuleStock.Module, ModuleVM>();
var moduletypeId = Convert.ToInt64(_db.ModuleTypes.Find(moduleVM.TypeName));
var module = new Sorama.DataModel.SIS.ModuleStock.Module
{
Id = moduleVM.Id,
ModuleId = moduleVM.ModuleId,
ModuleTypeId = moduletypeId,
DateEntered = moduleVM.DateEntered
};
//_db.Modules.Remove(module);//also this shows error, don't know why
Information("Your widget was deleted");
return RedirectToAction("ModuleList", "Module", new { area = "Hardware" });
}
编辑:根据答案,我尝试更改我的视图 在按下删除操作时,我在浏览器中收到此消息。
The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int64' for method 'System.Web.Mvc.ActionResult DeleteModule(Int64)' in 'AdminPortal.Areas.Hardware.Controllers.ModuleController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.
Parameter name: parameters
foreach
按下删除时,如何将我的语句中的 Id 从视图传递到控制器?