asp.net mvc从视图中排除ID

问题描述 投票:0回答:1

如何阻止用户编辑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。

asp.net-mvc
1个回答
3
投票

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

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

© www.soinside.com 2019 - 2024. All rights reserved.