【发布时间】:2016-03-08 15:55:36
【问题描述】:
我在 Razor 视图页面中使用 `@Html.Textbox("searchString")。我需要
中的文本框的这个值@Html.ActionLink("View Items", "Index", new { id = item.transaction_id, searchString = "Value of textbox"}).
当然,html 操作链接中的搜索字符串部分现在不工作,但我需要这个,因为我有根据搜索字符串工作的特定路线。
如何将文本框的值传递给操作链接?
我尝试的是
<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 在服务器端呈现。
更新
我在视图顶部有以下文本框:
@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", new { id = item.transaction_id }, FormMethod.Get)) 修改我的 @using (Html.BeginForm("Index", "trans_junction", 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。
我正在添加屏幕截图以便更好地理解。
这是没有搜索的索引视图。
【问题讨论】:
-
当您最后尝试了该代码时,结果如何?实际的客户端 JavaScript 是什么样子的,它执行时
value和link变量中的内容是什么?我强烈怀疑当代码尝试执行时,您的浏览器控制台显示 JavaScript 错误。你一定要看看那个。 -
如果您使用将文本框放入表单(使用
FormMethod.Get)并将提交按钮的样式设置为看起来像您想要的链接(无需脚本),您会发现这要容易得多.但是您的脚本所做的只是更新href属性。您需要取消默认重定向,然后调用location.href=url; -
@StephenMuecke 我需要一个文本框值,我可以通过操作链接传递它,以便它匹配 routeconfig 路由。
-
您不需要操作链接 - 将文本框放入表单中(使用
FormMethod.Get并将其提交给 GET 方法。 -
@StephenMuecke 我使用 @Html.beginform 和 FormMethod.Get 覆盖,现在我得到这种 url:localhost:57286/trans_junction/Index/74?searchString=52,正如你所见,我需要将 id 与搜索字符串一起传递。如果我像这样输入 url,localhost:57286/trans_junction/Index/74/52,我会得到想要的结果,但我不知道如何为这种 url 创建链接。所以我试图通过操作链接传递它。
标签: c# asp.net-mvc razor