![](/img/trans.png)
[英]Asp.Net Core Razor Pages Failed AJAX request after migrating to Version 3.1
[英]Razor not printing Values to screen after ASP 3.1 RazorPages AJAX Post Updates Model
您好,我正在使用 AJAX 調用在下拉選擇事件中更新模型。 模型已更新,當我逐步執行以下剃刀循環時,值存在。 但是,@if 語句中的任何內容都不會打印到屏幕上,甚至 H2 也不行。 div 只是空的... 想法?
@if (Model.FieldsRequiredOnStart != null)
{
foreach (var item in Model.FieldsRequiredOnStart)
{
for (int i = 0; i < @item.Inputs.Count(); i++)
{
<h2>Fields Required on Start</h2>
var x = @item.Inputs[i];
<span>@x.Name</span>
<input placeholder="@x.Name" maxlength="@x.MaxSize" type="@x.InputType"> <input />
}
}
}
function onSelect(e) {
let id = $("#wfDropdown").data("kendoDropDownList").value()
if (e.item) {
$('#wfDefId').val(id)
} else {
$('#wfDefId').val(id)
}
$.ajax({
type: 'Post',
url: '/CreateNewWorkflow?handler=RequiredInputs',
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
data: { Id: id },
success: function () {
}
});
}
成功編輯:我最終使用了部分視圖解決方案。 我的問題是當我之前嘗試部分方式時,我沒有發送更新的模型。 第二個答案也有效。 問題:如果您制作了部分內容,請務必刪除頂部的 @Page 引用,否則您將收到 Model is null 錯誤。
另外值得注意的是,我必須使用的 C# 語法與返回 Partial 視圖的答案中提供的略有不同。
public ActionResult OnPostRequiredInputs(int id)
{
//DO STUFF
//Refresh Model to pass to partial
IEnumerable<Razor.PageModels.CreateWorkflowNames> namelist = da.GetWfDefVersionNameAndIds();
var freshModel = new CreateNewWorkflowModel(_cache, _mapper, _wlog, _workflowFactory, _configuration)
{
FieldsRequiredOnStart = entityDefinitionFieldsList,
CreateWorkflowModel = namelist
};
return Partial("/Pages/_CreateNewWorkflowRequiredFieldsPartial.cshtml", freshModel);
}
假設您的 CreateNewWorkflow 控制器操作返回一個用新數據重新水化的模型,您應該能夠在 ajax 請求的 onSuccess 回調中設置該新數據。
我會這樣做以實現結果。
//Filename: YourView.cshtml
<div id="partialWrapper"></div>
//File name: _YourPartialView.cshtml
@if (Model.FieldsRequiredOnStart != null)
{
foreach (var item in Model.FieldsRequiredOnStart)
{
for (int i = 0; i < @item.Inputs.Count(); i++)
{
<h2>Fields Required on Start</h2>
var x = @item.Inputs[i];
<span>@x.Name</span>
<input placeholder="@x.Name" maxlength="@x.MaxSize" type="@x.InputType"> <input />
}
}
}
public IActionResult<YourModelClass> CreateNewWorkflow(YourRequestClass request) {
//your logic
//...
var rehydratedModel = new YourModelClass(); //actually fill this with data
return PartialView(rehydratedModel);
}
function onSelect(e) {
let id = $("#wfDropdown").data("kendoDropDownList").value()
if (e.item) {
$('#wfDefId').val(id)
} else {
$('#wfDefId').val(id)
}
$.ajax({
type: 'Post',
url: '/CreateNewWorkflow?handler=RequiredInputs',
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
data: { Id: id },
success: function (data) { //data represents your partial view
$('#partialWrapper').html(data) //set partial view
}
});
這是一個非常典型的使用 ajax 刷新剃刀頁面的流程。
在 ASP 3.1 RazorPages AJAX 發布更新模型后,Razor 不打印值到屏幕,div 只是空的
該問題與 Ajax 成功函數有關,根據您的代碼,我們可以看到您沒有執行任何操作以使用最新數據更新頁面。
一般在success函數中獲取到最新數據后,我們可以使用JQuery查找頁面元素並綁定最新數據或者填充新的頁面元素來替換舊數據。 您可以參考以下示例代碼:
<select id="ddl1" asp-for="CategoryId" asp-items="Model.Categories">
<option value="">Select Category</option>
</select>
<h4>SubCategories</h4>
@if (Model.SubCategories != null)
{
<table >
<tr><th>SubCategoryId</th><th>CategoryId</th><th>SubCategoryName</th></tr>
<tbody id="tbody">
@foreach (var item in Model.SubCategories)
{
<tr>
<td>@item.SubCategoryId</td>
<td>@item.CategoryId</td>
<td>@item.SubCategoryName</td>
</tr>
}
</tbody>
</table>
}
cshtml.cs 文件中的代碼:
private ICategoryService _categoryService;
public DDLpageModel(ICategoryService categoryService)
{
_categoryService = categoryService;
}
[BindProperty(SupportsGet = true)]
public int CategoryId { get; set; }
public int SubCategoryId { get; set; }
public SelectList Categories { get; set; }
public List<SubCategory> SubCategories { get; set; }
public void OnGet()
{
Categories = new SelectList(_categoryService.GetCategories(), nameof(Category.CategoryId), nameof(Category.CategoryName));
SubCategories = _categoryService.GetSubCategories(1).ToList();
}
public JsonResult OnGetSubCategories()
{
return new JsonResult(_categoryService.GetSubCategories(CategoryId));
}
然后,在Ajax成功函數中,找到該元素並設置值或動態添加最新數據的頁面元素並替換舊的。
@section scripts{
<script>
$(function () {
$("#ddl1").on("change", function () {
var categoryId = $(this).val();
//method 1: using JQuery Ajax get the latest data and update the main page content
$.ajax({
url: `?handler=SubCategories&categoryId=${categoryId}`,
contentType: 'application/json; charset=utf-8',
type: 'get',
dataType: 'json',
success: function (data) {
$("#tbody").html("");
//loop through the data and append new data to the tbody
$.each(data, function (i, item) {
$("#tbody").append("<tr><td>" + item.subCategoryId + "</td><td>" + item.categoryId + "</td><td>" + item.subCategoryName + "</td></tr>");
});
}
});
});
});
</script>
}
此外,您還可以創建一個 Partial 頁面(例如:_SubCategories.cshtml):
@model List<SubCategory>
<table class="table table-striped">
<tr><th>SubCategoryId</th><th>CategoryId</th><th>SubCategoryName</th></tr>
<tbody id="tbody">
@foreach (var item in Model)
{
<tr>
<td>@item.SubCategoryId</td>
<td>@item.CategoryId</td>
<td>@item.SubCategoryName</td>
</tr>
}
</tbody>
</table>
在主頁 .cshtml.cs 文件中,添加以下處理程序:
public PartialViewResult OnGetSubcategoryPartial()
{
var subcategories = _categoryService.GetSubCategories(CategoryId).ToList();
return Partial("_SubCategories", subcategories);
}
然后,使用 JQuery Ajax 調用上述處理程序並加載部分頁面:
<h2>Using Partial Page</h2>
<select id="ddl2" asp-for="CategoryId" asp-items="Model.Categories">
<option value="">Select Category</option>
</select>
<div id="output">
</div>
@section scripts{
<script>
$(function () {
$("#ddl2").on("change", function () {
var categoryId = $(this).val();
$.ajax({
url: `?handler=SubcategoryPartial&categoryId=${categoryId}`,
contentType: 'application/html; charset=utf-8',
type: 'get',
dataType: 'html',
success: function (result) {
$("#output").html("");
$("#output").append(result);
}
});
});
});
</script>
}
截圖是這樣的:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.