我有一个旨在从数据库中删除的视图.
该视图已正确填充.当我单击Delete按钮时,视图上的ID不会传递给控制器.当我在控制器中有一个断点时,已经从视图中收到了一个null
值.
在视图中,当我从这个<input asp-for="Form.Id" hidden />
中移除隐藏项时,Id
是可见的.然而,当我单击Delete按钮时,传递的Id
是null
.
我的模特:
namespace PricingParameters.Models
{
public class Form
{
[Key]
public int Id { get; set; }
[Required]
[Display(Name = "Branch")]
public int BranchId { get; set; } = 0;
[ValidateNeverAttribute]
public Branch Branch { get; set; }
[Required]
public int FormTypeId { get; set; } = 0;
[ValidateNeverAttribute]
public FormType FormType { get; set; }
[Required]
[Display(Name = "Form Cost")]
[DisplayFormat(DataFormatString = "{0:N2}", ApplyFormatInEditMode = true)]
public double Value { get; set; } = 0;
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
[Display(Name = "Modified Date")]
public DateTime ModifedDateTime { get; set; } = DateTime.Now;
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
[Display(Name = "Created Date")]
public DateTime CreatedDateTime { get; set; } = DateTime.Now;
}
}
我的视图模型:
namespace PricingParameters.Models.ViewModels
{
public class FormVM
{
public required Form Form { get; set; }
[ValidateNever]
public required IEnumerable<SelectListItem> BranchList { get; set; }
[ValidateNever]
public required IEnumerable<SelectListItem> FormTypeList { get; set; }
}
}
我的看法:
@model PricingParameters.Models.ViewModels.FormVM
@{
ViewData["Title"] = "Form Cost Delete";
}
<form method="post" asp-action="Delete">
<input asp-for="Form.Id" hidden />
<div class="border p-3 mt-4">
<div class="row pb-2">
<h2 class="text-primary">Delete Form Cost</h2>
<hr />
</div>
<div class="mb-3">
<label asp-for="Form.BranchId"></label>
<select asp-for="Form.BranchId" disabled asp-items="@Model.BranchList" class="form-select">
<option disabled selected>--Branch--</option>
</select>
</div>
<div class="mb-3">
<label asp-for="Form.FormTypeId"></label>
<select asp-for="Form.FormTypeId" disabled asp-items="@Model.FormTypeList" class="form-select">
<option disabled selected>--Form Type--</option>
</select>
</div>
<div class="mb-3">
<label asp-for="Form.Value"></label>
<input asp-for="Form.Value" disabled class="form-control" />
</div>
<button type="submit" class="btn btn-primary" style="width:150px">Delete</button>
<a asp-controller="Form" asp-action="Index" class="btn btn-secondary" style="width:150px">
Back to List
</a>
</div>
</form>
我的FormController
中的Delete
项行动:
// POST
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public IActionResult DeletePOST(int? id)
{
var obj = _unitOfWork.Form.GetFirstOrDefault(u => u.Id == id);
if (obj == null)
{
TempData["error"] = "Form Cost not deleted";
return RedirectToAction(nameof(Index));
}
_unitOfWork.Form.Remove(obj);
_unitOfWork.Save();
TempData["success"] = "Form Cost deleted successfully";
return RedirectToAction(nameof(Index));
}
这个代码几乎是另一种工作模式的逐个字符.