![](/img/trans.png)
[英]How to pass multiple actions in asp.net core 2.0 razor page using Url.Action
[英]How to pass textbox value using @Url.Action in ASP.NET MVC Core 2.2
在我看來,我有以下代碼:
<input type="text" id="createdDate" placeholder="dd/mm/yyyy" />
<a href="@Url.Action("GetRoomAccessHistory")">Download</a>
在我的控件中,我有以下代碼:
[HttpGet]
public async Task<IActionResult> GetRoomAccessHistory(DateTime createdDate)
{
// TO DO
}
在這種情況下,我想將文本框(createdDate)內的createdDate值傳遞給Url.Action(...),因此可以將其作為queryString傳遞給我的URL。 此操作作為GET請求調用,在GetRoomAccessHistory控制方法中,我應該獲取我的createdDate。
謝謝。
聚苯乙烯
我認為解決方案應該是這樣的:
<a href="@Url.Action("GetRoomAccessHistory", "Files", new { createdDate = ??? })" >Download</a>
我有一個可能的答案:
<form method="post" enctype="multipart/form-data" asp-action="GetRoomAccessHistory" id="formGetRoomAccessHistory">
...
<button type="button" id="downloadRoomAccessHistory"</button>
</form>
<script>
var form = document.getElementById("formGetRoomAccessHistory");
document.getElementById("downloadRoomAccessHistory").addEventListener("click", function () {
form.submit();
});
</script>
這正是我想要的並且可以工作,但是我試圖找到一個更好的解決方案,因為我在ASP.NET MVC中的經驗很低。
對於“ Get
請求”,請嘗試使用window.location.href
。
<input type = "text" id="createdDate" placeholder="dd/mm/yyyy" />
<a onclick = "navigate()" >
< input type="button" value='Download' />
</a>
<script type = 'text/javascript' >
function navigate()
{
var createdDate = document.getElementById('createdDate').value;
var url = "/Files/GetRoomAccessHistory?createdDate=" + createdDate;
window.location.href = url;
}
</script>
您的解決方案可以簡化為
<form method = "get" asp-controller="Files" asp-action="GetRoomAccessHistory" id="formGetRoomAccessHistory">
<input type = "text" name="createdDate" placeholder="dd/mm/yyyy" />
<button type = "button" onclick="myFunction()">Download</button>
</form>
<script>
function myFunction()
{
document.getElementById("formGetRoomAccessHistory").submit();
}
</script>
您為該工作使用了錯誤的工具。
由於Url.Action()
幫助程序在服務器端運行,因此它在第一次加載頁面時已經執行,並生成了固定的URL,該URL插入到頁面的HTML中。 它不知道用戶以后在文本框中輸入了什么。
如果要捕獲用戶輸入的數據,則使用表格更有意義。 在這種情況下,我使用了BeginForm標簽幫助程序來生成合適的HTML <form>
標簽:
<form asp-action="GetRoomAccessHistory" asp-controller="Files" method="get">
<input type="text" id="createdDate" name="createdDate" placeholder="dd/mm/yyyy" />
<input type="submit" value="Download"/>
</form>
提交后,這將對GetRoomAccessHistory操作的URL生成GET請求,並使用文本框中的值將createdDate
作為querystring變量附加。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.