我在 Razor View 页面中使用 `@Html.Textbox("searchString")。我需要
中文本框的这个值@Html.ActionLink("View Items", "Index", new { id = item.transaction_id, searchString = "Value of textbox"}).
当然,html 操作链接中的搜索字符串部分现在无法正常工作,但我需要它,因为我有根据搜索字符串工作的特定路线。
如何将文本框的值传递给操作链接?
我检查这个this , this , this和 this .
我试过的是
<script type = "text/javascript">
var value = document.getElementbyID("searchString").Text;
var link = @Html.ActionLink("View Items", "Index", new { id = item.transaction_id, searchString = -1});
link.replace(-1,value);
</script>
仍然没有运气。我了解 Razor 在服务器端呈现。
更新
我在 View 顶部有以下文本框:
@using (Html.BeginForm("Index", "trans_junction", FormMethod.Get))
{
<p>
Request No: @Html.TextBox("searchString")
<span><input type="submit" value="Search Request" /></span>
</p>
}
此文本框是用户可以在其中搜索项目的搜索框。
有一个Action链接如下:
@Html.ActionLink("View Items", "Index", new { id = item.transaction_id }) |
和路由配置:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}/{searchString}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional, searchString= UrlParameter.Optional }
);
}
}
现在我需要通过 actionlink 将值作为我的路线图传递。正如 StephenMuecke 在回答中所建议的,我尝试修改我的 @using (Html.BeginForm("Index", "trans_junction", FormMethod.Get))
和 @using (Html.BeginForm( "Index", "trans_junction", new { id = item.transaction_id }, FormMethod.Get))
但那里无法访问项目。
当用户点击搜索按钮时,url 为 http://localhost:57286/trans_junction/Index?searchString=20
如果用户点击操作链接 url 是 http://localhost:57286/trans_junction/Index/88
但我实际上需要的是 http://localhost:57286/trans_junction/Index/88/20
它保留搜索结果并传递 id。
我添加了屏幕截图以便更好地理解。
这是没有搜索的索引 View 。
最佳答案
与其手动尝试使用 javascript 操作链接,不如使用带有 method="get"
的表单。在你的循环中
@using (Html.BeginForm("Index", "trans_junction", new { id = item.transaction_id }, FormMethod.Get))
{
@Html.TextBox("SearchString")
<button type="submit">View Items"</button> // style as a link if desired
}
这将进行 GET 调用
[HttpGet]
public ActionResult Index(int id, string searchString)
假设你有一个特定的路由定义
url: "trans_junction/Index/{id}/{searchstring}",
defaults: new { controller = "trans_junction", action = "Index" }
编辑(根据更新的问题详情)
当您返回过滤结果时,您还需要将 searchString
的值传回 View ,以便在 ActionLink() 中可以使用 in 生成路由值
方法,例如
ViewBag.Filter = searchString;
return View(....);
然后修改链接到
@Html.ActionLink("View Items", "Index", new { id = item.transaction_id, searchString = ViewBag.Filter })
关于c# - 如何在同一 View 中获取 Razor 文本框的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35871982/