Asp.net mvc 3 路由值在.Net MVC3视图中消失

Asp.net mvc 3 路由值在.Net MVC3视图中消失,asp.net-mvc-3,routes,Asp.net Mvc 3,Routes,我有一个简单的控制器: public class TestController : Controller { public ActionResult Test(string r) { return View(); } } 我有simple View Test.cshtml: <h2>@ViewContext.RouteData.Values["r"]</h2> @u

我有一个简单的控制器:

public class TestController : Controller
    {
        public ActionResult Test(string r)
        {
            return View();
        }

    }
我有simple View Test.cshtml:

<h2>@ViewContext.RouteData.Values["r"]</h2>
        @using (Html.BeginForm("Test", "Test"))
        {
            <input type="text" name="r" />
            <button>Submit</button>
        }
我想做这样的事情:用户在输入中输入route值,按submit,控制器将他重定向到页面Test/value。但控制器每次只显示名为Test的页面。ViewContext.RouteData.Values[“r”]也为空。我签入调试,测试操作正确地接收r的用户值。 我怎样才能实现我的想法?
谢谢。

没有javascript,您无法完成此操作。提交
时存在两种方法:GET和POST。使用POST(默认设置)时,表单将发布到url,但输入字段中输入的所有数据都是POST正文的一部分,因此它不是url的一部分。使用GET时,输入字段数据是查询字符串的一部分,但格式为
/Test?r=somevalue

我不建议您尝试将用户输入作为路径的一部分发送,但如果您决定采用该路径,您可以订阅表单的提交事件并重写url:

$('form').submit(function() {
    var data = $('input[name="r"]', this).val();
    window.location.href = this.action + '/' + encodeURIComponent(data);
    return false;
});

就您所说的将表单发布到
Html.BeginForm(“Test”、“Test”)
而言,您将始终被发布回同一页面

解决方案可以是使用“RedirectToAction”(视图中)显式重定向到操作,也可以使用javascript更改表单的操作:

<input type="text" name="r" onchange="this.parent.action = '\/Test\/'+this.value"/>

我参加聚会迟到了,但我只是想发布一个解决方案供参考。让我们假设这个表单的输入不仅仅是一个强函数。假设还有其他输入,我们可以将表单的输入封装到模型中的一个类中,称为
TestModel
,其属性映射到表单输入的id

在我们的帖子中,我们重定向到get,在URL中传递我们需要的路由值。然后,可以使用TempData将任何其他数据传送到get

public class TestController : Controller
    {
        [HttpGet]
        public ActionResult Test(string r) 
        {
            TestModel model = TempData["TestModel"] as TestModel;
            return View(model);
        }

        [HttpPost]
        public ActionResult Test(string r,TestModel model) //some strongly typed class to contain form inputs
        {
            TempData["TestModel"] = model; //pass any other form inputs to the other action
            return RedirectToAction("Test", new{r = r}); //preserve route value
        }

    }

哦当然谢谢我创建了两个操作方法(HttpGet和HttpPost),并使用RedirectToAction从HttpPost方法到HttpGet方法。而且效果很好。谢谢
public class TestController : Controller
    {
        [HttpGet]
        public ActionResult Test(string r) 
        {
            TestModel model = TempData["TestModel"] as TestModel;
            return View(model);
        }

        [HttpPost]
        public ActionResult Test(string r,TestModel model) //some strongly typed class to contain form inputs
        {
            TempData["TestModel"] = model; //pass any other form inputs to the other action
            return RedirectToAction("Test", new{r = r}); //preserve route value
        }

    }