Редактирование и удаление пользователей

Последнее обновление: 31.10.2015

И, наконец, добавим функцию удаления и редактирования пользователей. Добавим в контроллер UserController следующие методы:

[HttpGet]
[Authorize(Roles = "Администратор")]
public ActionResult Edit(int id)
{
    User user = db.Users.Find(id);
    SelectList departments = new SelectList(db.Departments, "Id", "Name", user.DepartmentId);
    ViewBag.Departments = departments;
    SelectList roles = new SelectList(db.Roles, "Id", "Name", user.RoleId);
    ViewBag.Roles = roles;

    return View(user);
}

[HttpPost]
[Authorize(Roles = "Администратор")]
public ActionResult Edit(User user)
{
    if (ModelState.IsValid)
    {
        db.Entry(user).State = EntityState.Modified;
        db.SaveChanges();
        return RedirectToAction("Index");
    }
			
	SelectList departments = new SelectList(db.Departments, "Id", "Name");
    ViewBag.Departments = departments;
    SelectList roles = new SelectList(db.Roles, "Id", "Name");
    ViewBag.Roles = roles;
			
    return View(user);
}
[Authorize(Roles = "Администратор")]
public ActionResult Delete(int id)
{
    User user = db.Users.Find(id);
    db.Users.Remove(user);
    db.SaveChanges();
    return RedirectToAction("Index");
}

Оба действия также доступны только администратору. При передаче ролей в представление мы передаем в качестве четвертого параметра в конструктор SelectList текущее значение данного свойства объекта User: new SelectList(db.Roles, "Id", "Name", user.RoleId).

Представление Edit.cshtml буде выглядеть таким образом:

@model HelpDeskTrain.Models.User

@{
    ViewBag.Title = "Редактирование пользователя";
}

<h2>Редактирование пользователя</h2>

@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>Пользователь</legend>

        @Html.HiddenFor(model => model.Id)

        <div class="editor-label">
            @Html.LabelFor(model => model.Name)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Name)
            @Html.ValidationMessageFor(model => model.Name)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Login)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Login)
            @Html.ValidationMessageFor(model => model.Login)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Password)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Password)
            @Html.ValidationMessageFor(model => model.Password)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Position)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Position)
            @Html.ValidationMessageFor(model => model.Position)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.DepartmentId)
        </div>
        <div class="editor-field">
            @Html.DropDownListFor(model => model.DepartmentId, ViewBag.Departments as SelectList)
            @Html.ValidationMessageFor(model => model.DepartmentId)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.RoleId)
        </div>
        <div class="editor-field">
            @Html.DropDownListFor(model => model.RoleId, ViewBag.Roles as SelectList)
            @Html.ValidationMessageFor(model => model.RoleId)
        </div>

        <p>
            <input type="submit" value="Сохранить" />
        </p>
    </fieldset>
}
@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}
Помощь сайту
Юмани:
410011174743222
Перевод на карту
Номер карты:
4048415020898850