我正在为表单和表格使用 WebApi(ADO.NET 和带有 FetchApi 的 JS)。 正如您从图片中看到的那样,有 Id 79,然后是 Id = 0(刚刚创建了一个新行)。但在我重新加载页面后,Id 将呈现正常值。值得澄清的是,Ef Core 一切顺利
控制器中的发布方法:
[HttpPost]
public async Task<ActionResult<FormAbsence>> Create(FormAbsence model)
{
if (model != null)
{
var result = await _changeDataRepository.CreateDataAsync(model);
if (result == 0)
return this.StatusCode((int)HttpStatusCode.InternalServerError);
return Ok(model);
}
return BadRequest();
}
CreateDataAsync() 方法:
public async Task<int> CreateDataAsync(FormAbsence model)
{
_context.Connection();
int countChangeData = 0;
if (model == null)
return countChangeData;
var sqlExpression =
"INSERT INTO FormAbsence (reason, start_date, duration, discounted, description)" +
$" VALUES ({((int)model.Reason)}, '{model.StartDate.Date}', {model.Duration}, '{model.Discounted}', '{model.Description}')";
using (SqlConnection connection = new SqlConnection(_context.ConnectString))
{
await connection.OpenAsync();
SqlCommand command = new SqlCommand(sqlExpression, connection);
countChangeData = await command.ExecuteNonQueryAsync();
}
return countChangeData;
}
以及带有枚举的主类:
public class FormAbsence
{
public int Id { get; set; }
public Causes Reason { get; set; }
public DateTime StartDate { get; set; }
public int Duration { get; set; }
public bool Discounted { get; set; }
public string Description { get; set; }
}public enum Causes
{
Отпуск,
Больничный,
Прогул
}
至于html。
<form name="absenceForm">
<input name="id" type="hidden" value="0" />
<div class="form-group col-md-5">
<label for="validationDefault01">Причина отсутствия:</label>
<select class="form-select" name="reason" id="validationDefault01" aria-label="Default select example" required>
<option value="0">Отпуск</option>
<option value="1">Больничный</option>
<option value="2">Прогул</option>
</select>
<div class="valid-feedback">
Все хорошо!
</div>
<div class="invalid-feedback">
Это поле обязательно
</div>
</div>
<div class="panel-body">
<button type="submit" id="submit" class="btn btn-primary">Сохранить</button>
<a id="reset" class="btn btn-primary">Сбросить</a>
</div>
</form>
在 js 中我使用 fetchApi:
async function CreateFormAbsence(Freason, FstartDate, Fduration, Fdiscounted, Fdescription) {
const response = await fetch("/api/Values", {
method: "POST",
headers: { "Accept": "application/json", "Content-Type": "application/json" },
body: JSON.stringify({
reason: parseInt(Freason, 10),
startDate: FstartDate,
duration: Fduration,
discounted: Fdiscounted,
description: Fdescription
})
});
if (response.ok) {
let result = await response.json();
document.querySelector("tbody").append(row(result));
reset();
console.log("создана новая форма");
}
最后一行函数(添加一个新行并用数据填充它)和“保存”和重置按钮的事件
function row(form) {
let tr = document.createElement('tr');
tr.setAttribute("data-rowid", form.id);
let idTd = document.createElement("td");
idTd.append(form.id);
tr.append(idTd);
let reasonTd = document.createElement("td");
reasonTd.append(form.reason);
tr.append(reasonTd);
let startDateId = document.createElement("td");
startDateId.append(form.startDate);
tr.append(startDateId);
let durationId = document.createElement("td");
durationId.append(form.duration)
tr.append(durationId);
let discountedId = document.createElement("td");
discountedId.append(form.discounted);
tr.append(discountedId);
let descriptionId = document.createElement("td");
descriptionId.append(form.description);
tr.append(descriptionId)}
document.forms["absenceForm"].addEventListener("submit", e => {
e.preventDefault();
form = document.forms["absenceForm"];
let id = form.elements["id"].value;
let reason = form.elements["reason"].value;
let startDate = form.elements["startDate"].value;
let duration = form.elements["duration"].value;
let discounted = form.elements["discounted"].value;
let description = form.elements["description"].value;
if (id == 0) {
CreateFormAbsence(reason, startDate, duration, discounted, description)
} else {
EditFormAbsecne(id, reason, startDate, duration, discounted, description);
}
});