我正在使用 APS.NET Core MVC (.NET 5.0) 開發一個 Web 應用程式。我有一個物體(服務),它有另一個物體(OpeningHours)的動態串列。所以一項服務可以有不同的開放時間,例如:
- 從 08:00 到 20:00
- 08:00 至 13:00 和 17:00 至 20:00
您可以根據需要設定不同的時間段。我不知道如何實作這種情況并尋找解決方案,我發現如何將不同物體中的專案動態添加到 ASP.NET Core MVC 中的串列中,并遵循將其調整為我的物體的答案。簡化一點,這將是代碼:
模型(或視圖模型):
public class Service
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string Description { get; set; }
public List<ServiceOpeningHours> OpeningHours { get; set; } = new List<ServiceOpeningHours>();
}
public class ServiceOpeningHours
{
public TimeSpan From { get; set; }
public TimeSpan To { get; set; }
}
創建.cshtml(視圖):
@model MyWebApp.Services.Models.Service
...
<form asp-action="Create" name="createForm" id="createForm">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label class="control-label">Name</label>
<input asp-for="Name" class="form-control" />
<span asp-validation-for="Name" class="text-danger"></span>
</div>
<div class="form-group">
<label class="control-label">Description</label>
<input asp-for="Description" class="form-control" />
<span asp-validation-for="Description" class="text-danger"></span>
</div>
<fieldset>
<legend>Opening Hours</legend>
<div id="openingHoursContainer">
@foreach (ServiceOpeningHours item in Model.OpeningHours)
{
<partial name="_OpeningHourEditor" manifest model="item" />
}
</div>
</fieldset>
<div>
<div class="form-group">
<input id="addOpeningHourItem" type="button" value="Add Opening Hour" class="btn btn-primary" />
</div>
<div class="form-group">
<input type="submit" id="submit" value="Create" class="btn btn-primary" />
</div>
</div>
</form>
...
@section Scripts {
$('#addOpeningHourItem').click(function (event) {
event.preventDefault();
$.ajax({
async: true,
data: $('#form').serialize(),
type: 'POST',
url: '/Services/AddBlankOpeningHour',
success: function (partialView) {
$('#openingHoursContainer').append(partialView);
}
});
});
$('#submit').click(function (event) {
event.preventDefault();
var formData = new FormData();
formData.append("Name", $('input[name="Name"]').val());
formData.append("Description", $('input[name="Description"]').val());
$("input[name='From']").each(function (i) {
var from = $(this).val();
formData.append("OpeningHours[" i "].From", from);
});
$("input[name='To']").each(function (i) {
var to = $(this).val();
formData.append("OpeningHours[" i "].To", to);
});
formData.append("__RequestVerificationToken", $('form[name="createForm"] input[name="__RequestVerificationToken"]').val());
$.ajax({
method: 'POST',
url: '/Services/Create',
data: formData,
processData: false,
contentType: false,
success: function (returnValue) {
console.log('Success: ' returnValue);
}
});
});
}
_OpeningHourEditor.cshtml(營業時間專案的部分視圖):
@model MyWebApp.Models.ServiceOpeningHours
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label class="control-label">From</label>
<input asp-for="From" class="form-control" />
<span asp-validation-for="From" class="text-danger"></span>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label class="control-label">To</label>
<input asp-for="To" class="form-control" />
<span asp-validation-for="To" class="text-danger"></span>
</div>
</div>
</div>
In the javascript code a FormData is created and filled with all fields and the model successfully arrives at the Create action.
ServiceController:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Create(Service service)
{
if (ModelState.IsValid)
{
// Save data in data base...
return this.RedirectToAction("Index");
}
return View(service);
}
[HttpPost]
public ActionResult AddBlankOpeningHour()
{
return PartialView("_OpeningHourEditor", new ServiceOpeningHours());
}
With this code, when the Create action returns the response, it reaches the success block of $.ajax(), but this does not cause the page to reload with the new data.
I think you shouldn't do it with AJAX. How should I make the call so that everything works normally? That is, if the Name or Description fields are not filled in, the ModelState error message should be displayed, and if all goes well it should be redirected to the Index action.
uj5u.com熱心網友回復:
修改了提交腳本以洗掉 ajax 并最初更改輸入欄位的名稱,以便串列正確系結到模型。
$('#submit').click(function (event) {
// initially prevent form submit
event.preventDefault();
// loop through all input with name From, and change their name with index
$("input[name='From']").each(function (i) {
$(this).attr("name", "OpeningHours[" i "].From");
});
// loop through all input with name To, and change their name with index
$("input[name='To']").each(function (i) {
$(this).attr("name", "OpeningHours[" i "].To");
});
// submit the form
$("#createForm").submit();
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/435084.html
標籤:javascript asp.net asp.net-mvc asp.net-core-mvc form-data
下一篇:控制器類的回應
