asp.net mvc从视图中排除ID

时间:2018-05-05 10:52:59

标签: asp.net-mvc

如何阻止用户编辑ID并从编辑视图和控制器中删除ID?

所以我这是我的编辑视图:

    <div class="form-group">
    @Html.LabelFor(model => model.ItemName, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.EditorFor(model => model.ItemName, new { htmlAttributes = new { @class = "form-control" } })
        @Html.ValidationMessageFor(model => model.ItemName, "", new { @class = "text-danger" })
    </div>
</div>
<div class="form-group">
    @Html.LabelFor(model => model.Id, "Id", htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.DropDownList("Id", null, htmlAttributes: new { @class = "form-control" })
        @Html.ValidationMessageFor(model => model.Id, "", new { @class = "text-danger" })
    </div>
</div>

这就是控制器:

    [HttpPost]
    [ValidateAntiForgeryToken]
    [Authorize(Roles = "Member, Moderator, Admin, Owner")]
    public ActionResult Edit([Bind(Include = "ItemID,ItemName,Id")] Items items)
    {
        if (ModelState.IsValid && items.Id == User.Identity.GetUserId())
        {
            db.Entry(items).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        ViewBag.Id = new SelectList(db.Users, "Id", "Email", items.Id);
        return View(items);
    }

模特:

    public class Items
{
    [Key]
    public int ItemID { get; set; }
    [Required]
    public string ItemName { get; set; }

    [Editable(false)]
    public string Id { get; set; }

    public virtual ApplicationUser ItemUser { get; set; }
}

我希望用户只能更改model.ItemName。

1 个答案:

答案 0 :(得分:3)

如果某些crud操作需要Id,例如在控制器端更新/删除,那么我们无法将其删除,但可以防止编辑。

只需替换@Html.DropDownList to @Html.Hiddenfor(model => model.Id)@Html.Hidden("Id", {Value of Id})

即可