0

How can i prevent users from editing Id and remove Id from the edit view and controller ?

So i this my edit view:

    <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>

And this the controller:

    [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);
    }

And model:

    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; }
}

I want the users only to be able to change model.ItemName.

Kastan
  • 11
  • 1

1 Answers1

3

If Id is required for some kind of crud operation like update/delete at controller side then we can not remove it, but can prevent from editing.

Just replace @Html.DropDownList to @Html.Hiddenfor(model => model.Id) or @Html.Hidden("Id", {Value of Id})

CodeNotFound
  • 22,153
  • 10
  • 68
  • 69