我正在用Razor應用程式學習網路開發。我有一個頁面,PeopleIndex,其中一個表格顯示了一個人的串列,在每一行之后,首先有一個<a ...>來編輯人的資料,其次有一個<input ...>,我想從那里呼叫jQuery UI確認對話框(我在.cshtml中已經有代碼),從那里如果我點擊 "是 "按鈕,那個人的注冊資訊就會被洗掉,這就是,呼叫.cshtml.cs檔案中的Delete()方法。我知道這個程序不是一個提交動作,我這么說是因為我在互聯網上找到的所有與我的問題有關的東西都是關于 "表單方法=POST和型別=提交",所有這些都應該在另一個頁面中完成,而我只想在我的個人串列頁面中完成。但是,如果我錯了,我將聽取意見。 我附上我的PeopleIndex Razor頁面的兩個檔案:
。************* PeopleIndex.cshtml *****************
。@page
@model WebAppPersonas.Pages.PersonasIndexModel
@{
Layout = null;
}
<! DOCTYPE html>
<html lang="en">
<head title="Lista de personas"/span>>
<link rel="styleheet" href="~/lib/jquery-ui-1. 12.1.custom/jquery-ui.min.css"/span> />
< link rel="styleheet" href="~/lib/bootstrap/dist/css/bootstrap。 min.css" />
<link rel="styleheet" href="~/css/site. css" />
<script src="~/lib/jquery-ui-1. 12.1.custom/external/jquery/jquery.js"></script>
<script src="~/lib/jquery-ui-1. 12.1.custom/jquery-ui.min.js"></script>/span>
<script>
$(document).ready(function () {
// 確認對話框
$('#confirmDialog').dialog({
autoOpen: false,
寬度: 500,
高度:自動。
modal: true,
可調整大小: false,
按鈕。{
"是": function () {
$(".ui-dialog-buttonpane button:contains('Si')").button("disable")。
$(".ui-dialog-buttonpane button:contains('No')").button("disable")。
從.cs檔案中呼叫Delete()C#方法 // 都不知道這里要做什么
$(this).dialog("close")。
},
"No": function () {
$(this).dialog("close");
}
}
});
$('#deleteReg').click(function (e) {
e.preventDefault()。
$('#confirmDialog').dialog('open')。
});
});
</script>/span>
</head>/span>
<body>
<a asp-page=" 。 /InsertUpdate" class="btn btn-primary"> 添加人 </a>
<h2> 人員名單 </h2>
<table class="table">
<thead>/span>
<tr>/span>
<th> @Html.DisplayNameFor(Model => Model.people[0].Id) </th>
<th> @Html.DisplayNameFor(Model => Model.people[0].Name) </th>
<th> @Html.DisplayNameFor(Model => Model.people[0].Age) </th>
<th> @Html.DisplayNameFor(Model => Model.people[0].Email) </th>
</tr>/span>
</thead>/span>
<tbody>
@foreach (var item in Model.people)
{
<tr>
<td> @Html.DisplayFor(modelItem => item.Id) </td>
<td> @Html.DisplayFor(modelItem => item.Name) </td>
<td> @Html.DisplayFor(modelItem => item.Age) </td>
<td> @Html.DisplayFor(modelItem => item.Email) </td>
<td> a asp-page=" 。 /InsertUpdate" asp-route-id="@item. Id">更新</a>| < input type="button" value="Delete" onclick="I don't know what goes here" /> </td>
</tr>
}
</tbody>
</table>/span>
< div id="confirmDialog" title="確認洗掉">/span>
<p>您即將洗掉一個注冊表,您確定嗎?</p>
</div>/span>
</body>
</html>/span>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
********** PeopleIndex.cshtml.cs *****************
public void OnGet()
{
people = dataAccess.GetPeople()。
}
public ActionResult Delete(int? id) ?
{
dataAccess.DeletePerson(id.Value)。
return Redirect("./PeopleIndex") 。
}
我不得不剪掉.cshtml.cs檔案的標題,因為網站不允許我格式化該代碼,然后因為這個原因,網站不允許我發布這個問題。我希望現在它允許我發布問題。這非常復雜。我認為在不同的語言中格式化代碼的職責應該更容易,但是,......這就是有的東西...... 謝謝你。
**** 嗨,邁克爾 我用你給我的代碼編輯了這些檔案。
。 $('.deleteButton').click(function (e) {
e.preventDefault()。
const id = $(e.target).data("id")。
$('#confirmDialog').data("id", id);
$('#confirmDialog').dialog('open')。
});
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
。
<tbody>/span>
@foreach (var item in Model.people)
{
<tr>
<td> @Html.DisplayFor(modelItem => item.Id) </td>
<td> @Html.DisplayFor(modelItem => item.Name) </td>
<td> @Html.DisplayFor(modelItem => item.Age) </td>
<td> @Html.DisplayFor(modelItem => item.Email) </td>
<td> a asp-page=" 。 /InsertUpdate" asp-route-id="@item. Id">更新</a>| < button class="deleteButton" data-id="@item. Id">洗掉</button> </td>
</tr>
}
</tbody>/span>
<iframe name="sif3" sandbox="allow-form allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
所以現在還不能作業,但至少我們現在知道問題出在哪里。 我再次附上受影響的檔案和當前的更新,我不放.cs,因為只有它是正常的。 首先是.cshtml.cs(現在我們知道,當點擊deleteButton時,它并沒有進入JS功能。我試著把類換成名字,但還是一樣。
。@page
@model WebAppPersonas.Pages.PeopleIndexModel
@section Head
{
<link rel="styleheet" href="~/lib/jquery-ui-1. 12.1.custom/jquery-ui.min.css"/span> />
@*< link rel="styleheet" href="~/lib/bootstrap/dist/css/bootstrap。 min.css" />
<link rel="styleheet" href="~/css/site. css" />
<script src="~/lib/jquery-ui-1. 12.1.custom/external/jquery/jquery.js"></script> *@
<script src="~/lib/jquery-ui-1. 12.1.custom/jquery-ui.min.js"></script>/span>
<script>/span>
$(document).ready(function () {
/span>確認對話框。
$('#confirmDialog').dialog({
autoOpen: false,
width: 500,
高度: 自動。
modal: true,
resizable: false,
buttons: {
"Yes": function () {
$(".ui-dialog-buttonpane button:contains('Yes')").button("disable")。
$(".ui-dialog-buttonpane button:contains('No')").button("disable")。
DeletePerson($(this).data("id")。
$(this).dialog("close") 。
},
"No"。function () {
$(this).dialog("close")。
}
}
});
$('.deleteButton').click(function (e) {
e.preventDefault()。
const id = $(e.target).data("id") 。
$('#confirmDialog').data("id", id) 。
$('#confirmDialog').dialog('open')。
});
});
</script>>
<script>
const token = document. getElementsByName('__RequestVerificationToken')[0].nodeValue。
function DeletePerson(id) {
const formData = new FormData() 。
formData.append("id", id)。
fetch(window.location.href, {
method: 'DELETE'。
headers: { 'XSRF-TOKEN': token },
body: formData
})
.then(result => { window. location.reload(); })
.catch(error => alert("Error sending DELETE request.)
}
</script>>
}
< div id="confirmDialog" title="確認洗掉">/span>
<p> 你即將洗掉一個注冊表。你確定嗎?</p>你將要洗掉一個注冊表。
</div>/span>
<a asp-page=" 。 /InsertUpdate" class="btn btn-primary"> 添加人 </a>/span>
<h2> 人員串列 </h2>
<table class="table">
<thead>/span>
<tr>/span>
<th> @Html.DisplayNameFor(Model => Model.people[0].Id) </th>
<th> @Html.DisplayNameFor(Model => Model.people[0].Name) </th>
<th> @Html.DisplayNameFor(Model => Model.people[0].Age) </th>
<th> @Html.DisplayNameFor(Model => Model.people[0].Email) </th>
</tr>/span>
</thead>/span>
<tbody>
@foreach (var item in Model.people)
{
<tr>
<td> @Html.DisplayFor(modelItem => item.Id) </td>
<td> @Html.DisplayFor(modelItem => item.Name) </td>
<td> @Html.DisplayFor(modelItem => item.Age) </td>
<td> @Html.DisplayFor(modelItem => item.Email) </td>
<td> a asp-page=" 。 /InsertUpdate" asp-route-id="@item. Id">更新</a>| < button class="deleteButton" data-id="@item. Id">洗掉</button> </td>
</tr>
}
</tbody>
</table>/span>
@Html.AntiForgeryToken()
<iframe name="sif4" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
第二,_Layout.cshtml
。<!DOCTYPE html>
<html lang="en"/span>>
<head>/span>
<meta charset="utf-8" />
<meta name="viewport" content="width=device width, initial-scale=1. 0" />
<title>@ViewData["Title"] - WebAppPersonas</title>
@*<link rel="styleheet" href="~/lib/jquery-ui-1. 12.1.custom/jquery-ui.min.css"/span> />*@
< link rel="styleheet" href="~/lib/bootstrap/dist/css/bootstrap。 min.css" />
<link rel="styleheet" href="~/css/site. css" />
<script src="~/lib/jquery-ui-1. 12.1.custom/external/jquery/jquery.js"></script>
@*<script src="~/lib/jquery-ui-1. 12.1.custom/jquery-ui.min.js"></script> *@
@RenderSection("Head", false)
</head>
<body>/span>
<script src="~/lib/bootstrap/dist/js/bootstrap. bundle.min.js"></script>
<script src="~/js/site. js" asp-append-version="true">< /script>
<header>/span>
<nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3">
<div class="container">/span>
< a class="navbar-brand" asp-area=" asp-page="/Index"/span>> WebAppPersonas</a>。
< button class="navbar-toggler" type="button" data-toggle="collapse" data-target=" 。 navbar-collapse" aria-controls="navbarSupportedContent"。
aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"/span>> </span>>
</button>
<div class="navbar-collapse collapse d-sm-inline-flex flex-sm-row-reverse">/span>
<ul class="navbar-nav flex-grow-1">/span>
<li class="nav-item">/span>
< a class="nav-link text-dark" asp-area=" asp-page="/Index"/span>> 首頁</a>。
</li>/span>
<li class="nav-item">
< a class="nav-link text-dark" asp-area=" asp-page="/Privacy"> Privacy</a>。
</li>/span>
</ul>/span>
</div>/span>
</div>/span>
</nav>
</header>/span>
<div class="container">
< main role="main" class="pb-3">
@RenderBody()
</main>
</div>
<footer class="border-top footer text-muted" >
<div class="container">
© 2021 - WebAppPersonas - < a asp-area="" asp-page="/Privacy"/span>> Privacy</a>。
</div>/span>
</footer>
@*<script src="~/lib/jquery/dist/jquery。 min.js"></script>*@。
<script src="~/lib/bootstrap/dist/js/bootstrap. bundle.min.js"></script>
<script src="~/js/site. js" asp-append-version="true"></script>
@await RenderSectionAsync("Scripts", required: false)
</body>
</html>/span>
<iframe name="sif5" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
blockquote
uj5u.com熱心網友回復:
Razor頁面是一種服務器端技術。你不能在javascript中呼叫C#函式。相反 你可以提出一個請求。這個請求將被分配給你的Razor頁面中的一個方法,使用
為了說明這個問題,我們有一個簡單的PageModel:
為了說明這個問題,我們有一個簡單的PageModel。
public class Person
{
public int Id { get; set; }
public string Firstname { get; set; }
public string Lastname { get; set; }
}
public class PersonsModel : PageModel
{
private static List< Person> _persons = new List<Person>
{
new Person{Id = 1, Firstname = "FN1"/span>, Lastname = "LN1"/span>}。
new Person{Id = 2, Firstname = "FN2"/span>, Lastname = "LN2"/span>},
new Person{Id = 3, Firstname = "FN3"/span>, Lastname = "LN3"/span>},
new Person{Id = 4, Firstname = "FN4"/span>, Lastname = "LN4"/span>}.
};
public List<Person> Persons => _persons;
public void OnGet()
{
}
//從fetch中呼叫(JavaScript)
public IActionResult OnDelete(int id)
{
var person = _persons.Find(p => p.Id == id);
if (person == null) { return NotFound(); // HTTP 404 triggers .catch() in fetch }
_persons.Remove(person)。
return new NoContentResult(); // HTTP 204
}
}
正如你所看到的,OnDelete沒有回傳重定向,因為服務器回應沒有被解釋為 瀏覽器解釋。這取決于您對該回傳值的回應。
在我們的Razor視圖中,我們有一個人的串列和每個人的一個洗掉按鈕。
@page
@model RazorDemo.Pages.PersonsModel
@{
}
<ul>
@foreach (var p in Model.Person)
{
<li>@p.Id - @p.Firstname @p。 Lastname <button onclick="deletePerson(@p.Id)">onclick="deletePerson(@p.Id) Id)">Delete</button></li>
}
</ul>
@*生成一個帶有RequestVerificationToken的隱藏欄位*@。
@Html.AntiForgeryToken()
<script>
const token = document. getElementsByName('__RequestVerificationToken')[0].value。
//以multipart/form-data的形式發送DELETE請求(一個普通的HTML表單)。
function deletePerson(id){
// Crates a HTML form with one parameter (id)
const formData = new FormData() 。
formData.append("id", id)。
fetch(window.location.href, {
method: 'DELETE'。
headers: { 'XSRF-TOKEN': token },
body: formData
})
.catch(error => alert("Error sending DELETE request;)
}
</script>
服務器生成的HTML表單包含一個隱藏的輸入元素,其中有一個防偽造令牌 (request verification token, more information at www.learnrazorpages.com)。 我們必須通過使用@Html.AntiForgeryToken()手動創建這個元素。
JavaScript獲得這個令牌的值。在這之后,我們將創建一個普通 HTML 表格的有效載荷。 因為我們希望在服務器端使用標準的模型系結和驗證。
現在我們需要做一些配置,因為我們要在請求頭中發送防偽造令牌。
現在我們需要做一些配置,因為我們要在請求頭中發送防偽造令牌。
public void ConfigureServices(IServiceCollection services)
{
//其他服務
services.AddAntiforgery(o => o.HeaderName = "xsrf-token") 。
}
現在你可以洗掉一個人,但你的用戶界面不會重繪 。只有在重新加載后,被洗掉的 消失了。現在你到了需要一個JavaScript MVVM框架而不是JQuery的時候了。 一個小型的JavaScript框架是Knockout。一個JavaScript MVVM框架 基于來自你的服務器的json值生成html內容。你可以將你的人員串列 到客戶端,并將其存盤在一個陣列中。當你洗掉一個人時,你可以 你可以在該陣列中洗掉該人,而模板引擎將自動更新你的視圖。
Razor頁面支持JSON結果和不同的處理程式,所以你不需要一個單獨的控制器。
// GET Persons? handler=AllPersons
public IActionResult OnGetAllPersons()
{
return new JsonResult(Persons)。
}
使用jQuery UI
為了包括jQuery UI的參考,你可以在你的主布局(_Layout.cshtml)中定義一個部分。 默認模板使用bootstrap和jQuery。為了讓jQuery UI作業,你必須參考 捆綁版的jQuery,它與jQuery UI一起。我們還在head元素中定義了一個section,它可以被用于
我們還在head元素中定義了一個section,它可以被razor頁面使用。
_Layout.cshtml
<! DOCTYPE html>/span>
<html lang="en">
<head>/span>
<!-- 其他參考資料(bootstrap css, ...)-->
<script src="~/lib/jquery-ui-1. 12.1.custom/external/jquery/jquery.js"></script>
@RenderSection("Head", false)
</head>
<body>/span>
<!--你的布局與RenderBody() -->
<!-- 沒有提到JQUERY! -->
<script src="~/lib/bootstrap/dist/js/bootstrap. bundle.min.js"></script>
<script src="~/js/site. js" asp-append-version="true"></script>
@await RenderSectionAsync("Scripts", required: false)
</body>
</html>/span>
重要的是。洗掉(或注釋掉)lib/jquery/dist/jquery.min.js的參考。 的參考。
現在我們可以在Person頁面上添加一個對話框:
@page
@model RazorDemo.Pages.PersonsModel
@section Head
{
<link rel="styleheet" href="~/lib/jquery-ui-1. 12.1.custom/jquery-ui.min.css"/span> />
<script src="~/lib/jquery-ui-1. 12.1.custom/jquery-ui.min.js"></script>/span>
<script>/span>
$(document).ready(function () {
/span>確認對話框。
$('#confirmDialog').dialog({
autoOpen: false,
width: 500,
高度。"auto",
modal: true,
resizable: false,
buttons: {
"Yes": function () {
$(".ui-dialog-buttonpane button:contains('Si')").button("disable")。
$(".ui-dialog-buttonpane button:contains('No')").button("disable")。
//呼叫deletePerson與對話div的data-id。
deletePerson($(this).data("id") )。)
$(this).dialog("close") 。
},
"No"。function () {
$(this).dialog("close")。
}
}
});
$('.deleteButton').click(function (e) {
e.preventDefault()。
//我們有一個適用于所有按鈕的通用事件處理程式。
//所以我們必須查看事件源并讀取資料-id屬性。
const id = $(e.target).data("id") 。
//現在我們為<div id="confirmDialog">/span>創建一個資料屬性。
$('#confirmDialog').data("id", id)。
$('#confirmDialog').dialog('open')。
});
});
function deletePerson(id){
const token = document. getElementsByName('__RequestVerificationToken')[0].value。
const formData = new FormData()。
formData.append("id", id)。
fetch(window.location.href, {
method: 'DELETE'。
headers: { 'XSRF-TOKEN': token },
body: formData
})
.then(result => { window. location.reload(); }) //重新加載頁面。這不是AJAX,但它將完成這項作業。
.catch(error => alert("Error sending DELETE request;)
}
</script>>
}
< div id="confirmDialog" title="確認洗掉">/span>
<p> 你即將洗掉一個注冊表。你確定嗎?</p>
</div>/span>
<ul>/span>
@foreach (var p in Model.Personals)
{
<li>@p.Id - @p.Firstname @p。 Lastname <button class="deleteButton"/span> data-id="@p. Id">Delete</button>></li>>
}
</ul>
@*生成一個帶有RequestVerificationToken的隱藏欄位*@。
@Html.AntiForgeryToken()
代替onClick你可以使用一個通用的事件處理器(在jQuery中用.click()定義)。 因此,按鈕有一個data-id屬性。在事件處理程式中,我們檢索這個id $(e.target).data("id")并為對話框div動態地分配一個data-id屬性。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/319910.html
標籤:
