есть компонент справочник на vue и asp.net контроллер с методами, надо добавить…
- User
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
есть компонент справочник на vue и asp.net контроллер с методами, надо добавить возможность редактирования записей, использую linq2db
<button
@click="startAdding"
:disabled="!selectedReference || !selectedOption?.canAdd"
class="add-button"
>
+ Добавить запись
</button>
</div>
<div class="table-container">
<table
style="width: 100%"
class="pure-table pure-table-striped"
v-if="tableData.length || isAdding"
>
<thead>
<tr>
<th
v-for="header in currentHeaders"
:key="header.value"
:style="{ width: header.width || 'auto' }"
>
{{ header.text }}
</th>
</tr>
</thead>
<tbody>
<!-- Строка добавления -->
<tr
v-if="isAdding"
class="adding-row"
:class="{ 'invalid-row': hasErrors }"
>
<td v-for="header in currentHeaders" :key="header.value">
<input
v-if="header.editable"
v-model="newItem[header.value]"
:placeholder="header.text"
:class="{ invalid: !isFieldValid(header.value) }"
@keyup.enter="saveRow"
ref="inputFields"
/>
<span v-else class="non-editable">(авто)</span>
</td>
</tr>
<!-- Существующие записи -->
<tr v-for="(item, index) in tableData" :key="index">
<td v-for="header in currentHeaders" :key="header.value">
{{ formatValue(item[header.value], header.value) }}
</td>
</tr>
</tbody>
</table>
<div v-if="!tableData.length && !isAdding" class="no-data">
Нет данных для отображения
</div>
</div>
public async Task<List<ApkDto>> Apks() =>
await _connectionAlphaNames
.Apks.Select(a => new ApkDto { ApkId = a.ApkId, ApkName = a.ApkName })
.ToListAsync();
public async Task<List<CodeCategoryDto>> CodeCategories() =>
await _connectionAlphaNames
.CodeCategories.Select(c => new CodeCategoryDto
{
CodeCategoryId = c.CodeCategoryId,
CodeCategoryName = c.CodeCategoryName
})
.ToListAsync();
public async Task<List<LegalEntityTypeDto>> LegalEntityTypes() =>
await _connectionAlphaNames
.LegalEntityTypes.Select(l => new LegalEntityTypeDto
{
LegalEntityTypeId = l.LegalEntityTypeId,
LegalEntityTypeName = l.LegalEntityTypeName
})
.ToListAsync();
public async Task<List<OperatorDto>> Operators() =>
await _connectionAlphaNames
.Operators.Select(o => new OperatorDto
{
OperatorId = o.OperatorId,
OperatorName = o.OperatorName
})
.ToListAsync();
public async Task<List<SmsDistributionTypeDto>> SmsDistributionTypes() =>
await _connectionAlphaNames
.SmsDistributionTypes.Select(s => new SmsDistributionTypeDto
{
DistributionTypeId = s.DistributionTypeId,
DistributionTypeName = s.DistributionTypeName
})
.ToListAsync();
public async Task<List<ExceptionLogDto>> ExceptionLogs() =>
await _connectionAlphaNames
.ExceptionLogs.Select(e => new ExceptionLogDto
{
ExceptionLogId = e.ExceptionLogId,
Message = e.Message,
UserName = e.Users != null ? e.Users.FullName : null,
TimeStamp = e.TimeStamp
})
.OrderByDescending(x => x.ExceptionLogId)
.ToListAsync();
[HttpPost]
public async Task AddApk([FromBody] ApkDto dto) =>
await _connectionAlphaNames.InsertAsync(new Apk { ApkName = dto.ApkName });
[HttpPost]
public async Task AddCodeCategory([FromBody] CodeCategoryDto dto) =>
await _connectionAlphaNames.InsertAsync(
new CodeCategory { CodeCategoryName = dto.CodeCategoryName }
);
[HttpPost]
public async Task AddLegalEntityType([FromBody] LegalEntityTypeDto dto) =>
await _connectionAlphaNames.InsertAsync(
new LegalEntityType { LegalEntityTypeName = dto.LegalEntityTypeName }
);
[HttpPost]
public async Task AddOperator([FromBody] OperatorDto dto) =>
await _connectionAlphaNames.InsertAsync(
new Operator { OperatorName = dto.OperatorName }
);
[HttpPost]
public async Task AddSmsDistributionType([FromBody] SmsDistributionTypeDto dto) =>
await _connectionAlphaNames.InsertAsync(
new SmsDistributionType { DistributionTypeName = dto.DistributionTypeName }
);
Чтобы добавить возможность редактирования записей в вашем компоненте справочника, нам нужно внести изменения как во Vue-компоненте, так и в ASP.NET контроллере. Ниже пошаговое руководство:
1. Изменения в ASP.NET контроллере
Сначала добавим методы обновления данных в контроллере. Для каждого типа справочника создадим метод Update{EntityName} (например, UpdateApk, UpdateCodeCategory и т.д.).
Вот примеры этих методов:
[HttpPut("{id}")]
public async Task UpdateApk(int id, [FromBody] ApkDto dto)
{
await _connectionAlphaNames.Apks
.Where(a => a.ApkId == id)
.Set(a => a.ApkName, dto.ApkName)
.UpdateAsync();
}
[HttpPut("{id}")]
public async Task UpdateCodeCategory(int id, [FromBody] CodeCategoryDto dto)
{
await _connectionAlphaNames.CodeCategories
.Where(c => c.CodeCategoryId == id)
.Set(c => c.CodeCategoryName, dto.CodeCategoryName)
.UpdateAsync();
}
[HttpPut("{id}")]
public async Task UpdateLegalEntityType(int id, [FromBody] LegalEntityTypeDto dto)
{
await _connectionAlphaNames.LegalEntityTypes
.Where(l => l.LegalEntityTypeId == id)
.Set(l => l.LegalEntityTypeName, dto.LegalEntityTypeName)
.UpdateAsync();
}
[HttpPut("{id}")]
public async Task UpdateOperator(int id, [FromBody] OperatorDto dto)
{
await _connectionAlphaNames.Operators
.Where(o => o.OperatorId == id)
.Set(o => o.OperatorName, dto.OperatorName)
.UpdateAsync();
}
// Для SmsDistributionType (если понадобится)
[HttpPut("{id}")]
public async Task UpdateSmsDistributionType(int id, [FromBody] SmsDistributionTypeDto dto)
{
await _connectionAlphaNames.SmsDistributionTypes
.Where(s => s.DistributionTypeId == id)
.Set(s => s.DistributionTypeName, dto.DistributionTypeName)
.UpdateAsync();
}
Обратите внимание:
[HttpPut("{id}")] указывает, что метод обрабатывает HTTP PUT запросы, а {id} — параметр маршрута (идентификатор редактируемой записи).linq2db для обновления только нужного поля (ApkName, CodeCategoryName и т.д.) по заданному id.2. Изменения во Vue-компоненте
Теперь обновим Vue-компонент, чтобы добавить:
Обновлённый шаблон (template)
Добавьте столбец с кнопками "Редактировать" и измените строки таблицы:
<tbody>
<!-- Строка добавления (оставляем без изменений) -->
<tr
v-if="isAdding"
class="adding-row"
:class="{ 'invalid-row': hasErrors }"
>
<!-- ... код строки добавления остаётся прежним ... -->
</tr>
<!-- Существующие записи -->
<tr v-for="(item, index) in tableData" :key="index">
<template v-if="editingId === item[getPrimaryKey(selectedReference)]">
<!-- Режим редактирования -->
<td v-for="header in currentHeaders" :key="header.value">
<input
v-if="header.editable"
v-model="editItem[header.value]"
:class="{ invalid: !isFieldValid(header.value) }"
/>
<span v-else class="non-editable">{{ formatValue(item[header.value], header.value) }}</span>
</td>
<td>
<button @click="saveEdit" class="save-button">Сохранить</button>
<button @click="cancelEdit" class="cancel-button">Отмена</button>
</td>
</template>
<template v-else>
<!-- Режим просмотра -->
<td v-for="header in currentHeaders" :key="header.value">
{{ formatValue(item[header.value], header.value) }}
</td>
<td>
<button
@click="startEditing(item)"
:disabled="!selectedOption?.canEdit"
class="edit-button"
>
Редактировать
</button>
</td>
</template>
</tr>
</tbody>
Добавьте стили для новых кнопок:
.edit-button {
background: #007bff;
color: white;
border: none;
padding: 6px 12px;
border-radius: 4px;
cursor: pointer;
}
.save-button {
background: #28a745;
color: white;
border: none;
padding: 6px 12px;
border-radius: 4px;
margin-right: 4px;
}
.cancel-button {
background: #dc3545;
color: white;
border: none;
padding: 6px 12px;
border-radius: 4px;
}
Обновляем скрипт (script setup)
Добавляем новые состояния и методы:
// Новое состояние для редактирования
const editingId = ref<number | null>(null);
const editItem = ref<Record<string, any>>({});
// Разрешаем редактирование для справочников (добавляем canEdit в ReferenceOption)
interface ReferenceOption {
id: keyof typeof headersConfig;
name: string;
canAdd: boolean;
canEdit: boolean;
}
const referenceOptions: ReferenceOption[] = [
{ id: 'apks', name: 'APK', canAdd: true, canEdit: true },
{ id: 'codeCategories', name: 'Категории кодов', canAdd: true, canEdit: true },
{ id: 'legalEntityTypes', name: 'Типы юрлиц', canAdd: true, canEdit: true },
{ id: 'operators', name: 'Операторы', canAdd: true, canEdit: true },
{ id: 'exceptionLogs', name: 'Логи ошибок', canAdd: false, canEdit: false },
];
// Метод для определения первичного ключа справочника
const getPrimaryKey = (reference: keyof typeof headersConfig): string => {
const mapping: Record<keyof typeof headersConfig, string> = {
apks: 'apkId',
codeCategories: 'codeCategoryId',
legalEntityTypes: 'legalEntityTypeId',
operators: 'operatorId',
exceptionLogs: 'exceptionLogId',
default: '',
};
return mapping[reference];
};
// Начало редактирования
const startEditing = (item: any) => {
editingId.value = item[getPrimaryKey(selectedReference.value)];
editItem.value = { ...item }; // Клонируем объект для редактирования
};
// Сохранение редактирования
const saveEdit = async () => {
const id = editingId.value;
if (!id) return;
try {
switch (selectedReference.value) {
case 'apks':
await _AdminController.updateApk(id, editItem.value as ApkDto);
break;
case 'codeCategories':
await _AdminController.updateCodeCategory(id, editItem.value as CodeCategoryDto);
break;
case 'legalEntityTypes':
await _AdminController.updateLegalEntityType(id, editItem.value as LegalEntityTypeDto);
break;
case 'operators':
await _AdminController.updateOperator(id, editItem.value as OperatorDto);
break;
}
editingId.value = null; // Выходим из режима редактирования
await fetchData(); // Обновляем данные
} catch (err) {
console.error('Ошибка сохранения:', err);
}
};
// Отмена редактирования
const cancelEdit = () => {
editingId.value = null;
};
3. Добавляем API-методы во Vue-клиенте
В файле _AdminController.ts добавляем новые методы для обновления данных:
static async updateApk(id: number, dto: ApkDto): Promise<void> {
await http.put(`/admin/apks/${id}`, dto);
}
static async updateCodeCategory(id: number, dto: CodeCategoryDto): Promise<void> {
await http.put(`/admin/codeCategories/${id}`, dto);
}
static async updateLegalEntityType(id: number, dto: LegalEntityTypeDto): Promise<void> {
await http.put(`/admin/legalEntityTypes/${id}`, dto);
}
static async updateOperator(id: number, dto: OperatorDto): Promise<void> {
await http.put(`/admin/operators/${id}`, dto);
}
Что мы сделали:
Update{EntityName}, которые обрабатывают HTTP PUT запросы и обновляют записи в БД через linq2db.input-ы).Теперь вы можете:
Если возникнут ошибки (например, валидация не прошла), строка останется в режиме редактирования. Приятного тестирования! 😊