[英]How to overwrite one model property in ASP.Net core
我有一個有 10 個屬性的模型。 A、B、C 等等...
屬性A
是一個數組。
對於數組中的每個值,我生成一個這樣的標簽:
<div class="col-sm-10 row">
@foreach (var item in Model.A)
{
<div class="col-sm-1 right-buffer">
<a href="@item.Value"><i class="" aria-hidden="true">@item.Text</i></a>
</div>
}
</div>
當用戶單擊某個鏈接時,我應該將其重定向到同一頁面,但某些模型屬性已更改。 例如:
當前網址: my/controller/someaction?name=Alex&age=20&from=fr&CurrentA=
with model ?name=Alex&age=20&from=fr&CurrentA=
如果用戶點擊帶有文本foo
<a>
它應該被重定向到my/controller/someaction?name=Alex&age=20&from=fr&CurrentA=foo
然后就是網上的點擊<a>
文字bar
,它現在應當對重定向my/controller/someaction?name=Alex&age=20&from=fr&CurrentA=bar
因此,應保留整個查詢字符串(一個參數除外)以將當前模型狀態發送到服務器,而我想設置一個值並將其重定向到同一頁面但具有新值。
最終,它應該像postback with one extra value setted to model
一樣postback with one extra value setted to model
是否有可能,或者我應該使用 JS 並自己執行所有操作?
我手動解決了這個問題:
首先,為模型中的每個屬性創建隱藏字段:
<form asp-controller="search" asp-action="index" method="get" role="form" id="searchForm" asp-antiforgery="false">
<input asp-for="SessionId" type="hidden" name="sessionId" value="@Model.SessionId" />
<input asp-for="Quantity" type="hidden" name="quantity" value="@Model.Quantity"/>
<input asp-for="SortField" type="hidden" name="sortField" value="@Model.SortField"/>
<input asp-for="IsAscending" type="hidden" name="IsAscending" value="@Model.IsAscending" />
<input asp-for="Offset" type="hidden" name="offset" value="0" />
...
</form>
然后,使用JS替換隱藏字段中的值,然后提交表單。 來自輸入的值將在查詢字符串中自動轉換,因此一切正常:
function sortDocuments(sortField) {
var sField = document.getElementById('SortField');
var isDescending = document.getElementById('IsAscending');
if (sField.value === sortField) {
if (isDescending.value.toUpperCase() === 'FALSE') {
isDescending.value = 'TRUE';
} else {
sField.value = 'rank';
isDescending.value = 'FALSE';
}
} else {
sField.value = sortField;
isDescending.value = 'FALSE';
}
document.getElementById('searchForm').submit();
}
不是很優雅,但它完成了它的工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.