Как обновить записи, используя модель представления в ASP. NET MVC, используя Entity Framework - PullRequest
0 голосов
/ 03 мая 2020

В настоящее время я работаю с Entity Framework и до сих пор могу передавать данные из модели в модель представления. Я хочу обновить записи непосредственно из модели представления, а затем эти записи обновляются в базе данных. Я пытаюсь создать CRUD с пользователями сущностей.

Я надеюсь, что кто-то может подсказать или дать мне совет, как это сделать

введите описание изображения здесь

введите описание изображения здесь

Код:

// my controller
public class AdministrationController : Controller
{
    private readonly UserManager<ApplicationUser> userManager;
    private readonly ApplicationDbContext _context;

    public AdministrationController(UserManager<ApplicationUser> userManager)
    {
        this.userManager = userManager;
    }

    [HttpGet]
    public IActionResult Index()
    {
        // with this I get all the users
        var users = userManager.Users;
        return View(users);
    }

    // with this method, passed the information to the modal window
    public async Task<List<ApplicationUser>> GetUsuario(string id)
    {
        List<ApplicationUser> usuario = new List<ApplicationUser>();
        //var appUsuario = await _context.ApplicationUser.SingleOrDefaultAsync(m => m.Id == id);
        var appUsuario = await userManager.FindByIdAsync(id);
        usuario.Add(appUsuario); 
        return usuario;
    }

    [HttpPost]   //my problem is here because when I tried to Call to the modal window does not work
    public async Task<string> EditUsuario(string id, string userName, string email,
       string phoneNumber, int accessFailedCount, string concurrencyStamp, bool emailConfirmed,
       bool lockoutEnabled, DateTimeOffset lockoutEnd, string normalizedEmail,
       string normalizedUserName, string passwordHash, bool phoneNumberConfirmed,
       string securityStamp, bool twoFactorEnabled, ApplicationUser applicationUser)
    {
        var resp = "";

        try
        {
            applicationUser = new ApplicationUser
            {
                Id = id,
                UserName = userName,
                Email = email,
                PhoneNumber = phoneNumber,
                EmailConfirmed = emailConfirmed,
                LockoutEnabled = lockoutEnabled,
                LockoutEnd = lockoutEnd,
                NormalizedEmail = normalizedEmail,
                NormalizedUserName = normalizedUserName,
                PasswordHash = passwordHash,
                PhoneNumberConfirmed = phoneNumberConfirmed,
                SecurityStamp = securityStamp,
                TwoFactorEnabled = twoFactorEnabled,
                AccessFailedCount = accessFailedCount,
                ConcurrencyStamp = concurrencyStamp
            };

            // Actualizamos los datos
            _context.Update(applicationUser);
            await _context.SaveChangesAsync();
            resp = "Save";
        }
        catch
        {
            resp = "No Save";
        }

        return resp;
    }
}

Модель:

public class EditUserViewModel
{
    public EditUserViewModel()
    {
        Claims = new List<string>();
        Roles = new List<string>();
    }

    public string Id { get; set; }

    [Required]
    public string UserName { get; set; }

    [Required]
    [EmailAddress]
    public string Email { get; set; }

    public string PhoneNumber { get; set; }

    public List<string> Claims { get; set; }

    public IList<string> Roles { get; set; }
}

Мой Javascript код:

// Write your JavaScript code.
$('#modalEditar').on('shown.bs.modal', function () {
    $('#myInput').focus()
})

function getUsuario(id, action) {
    $.ajax({
        type: "POST",
        url: action,
        data: { id },
        success: function (response) {
            mostrarUsuario(response);
        }

    });
}

var items;
//Variables globales por cada propiedad del usuario
var id;
var userName;
var email;
var phoneNumber;

var accessFailedCount;
var concurrencyStamp;
var emailConfirmed;
var lockoutEnabled;
var lockoutEnd;
var normalizedUserName;
var normalizedEmail;
var passwordHash;
var phoneNumberConfirmed;
var securityStamp;
var twoFactorEnabled;

function mostrarUsuario(response) {
    items = response;
    $.each(items, function (index, val) {
        $('input[name=Id]').val(val.id);
        $('input[name=UserName]').val(val.userName);
        $('input[name=Email]').val(val.email);
        $('input[name=PhoneNumber]').val(val.phoneNumber);
    });
}

function editarUsuario(action) {
    //Obtenemos los datos del input respectivo del formulario
    id = $('input[name=Id]')[0].value;
    email = $('input[name=Email]')[0].value;
    phoneNumber = $('input[name=PhoneNumber]')[0].value;

    $.each(items, function (index, val) {
        accessFailedCount = val.accessFailedCount;
        concurrencyStamp = val.concurrencyStamp;
        emailConfirmed = val.emailConfirmed;
        lockoutEnabled = val.lockoutEnabled;
        lockoutEnd = val.lockoutEnd;
        userName = val.userName;
        normalizedUserName = val.normalizedUserName;
        normalizedEmail = val.normalizedEmail;
        passwordHash = val.passwordHash;
        phoneNumberConfirmed = val.phoneNumberConfirmed;
        securityStamp = val.securityStamp;
        twoFactorEnabled = val.twoFactorEnabled;
    });
    $.ajax({
        type: "POST",
        url: action,
        data: {
            id, userName, email, phoneNumber, accessFailedCount,
            concurrencyStamp, emailConfirmed, lockoutEnabled, lockoutEnd,
            normalizedEmail, normalizedUserName, passwordHash, phoneNumberConfirmed,
            securityStamp, twoFactorEnabled
        },
        success: function (response) {
            if (response == "Save") {
                window.location.href = "Usuarios";
            }
            else {
                alert("No se puede editar los datos del usuario");
            }
        }
    });

Мой взгляд:

@model IEnumerable<ApplicationUser>

@{
    ViewBag.Title = "All Users";
}

<h1>All Users</h1>

@*@if (Model.Any())
    {
        <a asp-action="Register" asp-controller="Account"
           class="btn btn-primary mb-3" style="width:auto">
            Add new user
        </a>*@


<table class="table">
    <thead>
        <tr>
            <th>Name</th>

            <th>Email</th>
            <th>phone</th>

        </tr>
    </thead>
    <tbody>
        @foreach (var user in Model)
        {

        <tr>

            <td> @Html.DisplayFor(modelItem => user.UserName)   </td>
            <td> @Html.DisplayFor(modelItem => user.Email)  </td>
            <td> @Html.DisplayFor(modelItem => user.PhoneNumber)  </td>

            @*<td><a asp-action="EditUser" asp-controller="Administration" asp-route-id="@user.Id" class="btn btn-primary">Editar</a></td>*@
            <td><a class="btn btn-success" data-toggle="modal" data-target="#modalEditar" onclick="getUsuario('@user.Id','administration/GetUsuario')">Editar</a></td>

        </tr>

        }
    </tbody>
</table>


<!-- Modal -->
<div class="modal fade" id="modalEditar" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" id="myModalLabel">Editar Usuario</h4>
            </div>
            <div class="modal-body">
                <form>
                    <div asp-validation-summary="ModelOnly" class="text-danger"></div>
                    <input type="hidden" name="Id" id="id" />
                    <div class="form-group">
                        <label for="Id" class="control-label">Id</label>
                        <input readonly name="Id" id="Id" class="form-control" />
                    </div>
                    <div class="form-group">
                        <label for="UserName" class="control-label">Usuario</label>
                        <input readonly name="UserName" id="UserName" class="form-control" />
                    </div>
                    <div class="form-group">
                        <label for="Email" class="control-label">Email</label>
                        <input name="Email" id="Email" class="form-control" />
                    </div>
                    <div class="form-group">
                        <label for="PhoneNumber" class="control-label">Teléfono</label>
                        <input name="PhoneNumber" id="PhoneNumber" class="form-control" />
                    </div>
                </form>

            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Cerrar</button>
                @*<button type="button" class="btn btn-primary">Guardar Cambios</button>*@
                <button type="button" class="btn btn-primary" onclick="editarUsuario('administration/EditUsuario')">Guardar</button>
            </div>
        </div>
    </div>
</div>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...