繁体   English   中英

如何在ASP.NET MVC Core 2.2中使用@ 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM