【问题标题】:ASP.NET MVC - Rewriting FormMethod.Get querystring?ASP.NET MVC - 重写 FormMethod.Get 查询字符串?
【发布时间】:2009-10-15 18:24:11
【问题描述】:

我有一个简单的表单,只有一个文本框和一个提交按钮。该表单基本上将文本框中的值作为查询字符串发送到不同的页面。当我点击提交按钮时,查询字符串是这种格式,例如:

mysite.com/?TargetCode=Test1

我希望它以这种格式显示:mysite.com/Test1

我的HomeController 中已经有一个将“TargetCode”作为查询字符串的操作,并且我已经为此在Global.ascx.cs 中设置了一个路由。我应该怎么做才能重新编写查询字符串,使其在 URL 中没有“?TargetCode =”?这是我所拥有的表单的代码:

<% using (Html.BeginForm("Index", "Home", FormMethod.Get, new { id = "CodeForm" }))

【问题讨论】:

  • 实际上我的另一个问题是关于我的 Index(string Target) 操作没有获取查询字符串,它现在工作正常。这个问题是关于如何重写我的 URL。谢谢:)

标签: asp.net-mvc routing query-string


【解决方案1】:

我认为您必须使用 jQuery 进行提交,否则您将依赖于浏览器如何构造 URL。 更新在验证插件中包含一个挂钩。

$('#CodeForm').submit( function() {
     var $form = $(this);
     if ($form.valid()) {
        window.location.href = $form.attr('action')
                                  + '/'
                                  + $('[name=TargetCode]').val();
     }
     return false;
});

【讨论】:

  • 嗨 tvanfosson,我还在使用 jQuery 验证库来确保文本框在其中具有值(必填字段。)当我使用您发布的 jQuery 函数时,它绕过了验证.这是我所拥有的: $(document).ready(function() { $("#CodeForm").validate(); $('#CodeForm').submit(function() { window.location.href = ' /' + $('[name=TargetCode]').val(); return false; }); });谢谢,肯尼。
  • 所以在提交之前检查表单是否有效。
猜你喜欢
  • 2012-06-30
  • 2012-03-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-01
  • 1970-01-01
  • 2014-03-27
相关资源
最近更新 更多