2011-08-11 26 views
0

我有簡單的控制器:路線值觀淨MVC3基本消失

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

    } 

我簡單查看Test.cshtml:在Global.asax中

<h2>@ViewContext.RouteData.Values["r"]</h2> 
     @using (Html.BeginForm("Test", "Test")) 
     { 
      <input type="text" name="r" /> 
      <button>Submit</button> 
     } 

我有途徑規則:

routes.MapRoute(
      null, 
      "Test/{r}", 
      new { action = "Test", controller = "Test", 
       r = UrlParameter.Optional } 
     ); 

我想做這樣的事情:用戶輸入路徑值,按提交和控制器將他重定向到頁面測試/值。但控制器每次只顯示名稱爲Test的頁面。 ViewContext.RouteData.Values [「r」]也是空的。我檢查調試,測試操作正確接收r的用戶值。 我怎樣才能實現我的想法? 謝謝。

回答

0

你不能這樣做沒有JavaScript。提交<form>時存在兩種類型的方法:GET和POST。當您使用POST(這是默認設置)時,表單會發送到url,但輸入字段中輸入的所有數據都是POST正文的一部分,因此它不是url的一部分。當您使用GET時,輸入字段數據是查詢字符串的一部分,但形式爲/Test?r=somevalue

我不建議你嘗試發送用戶輸入路徑的一部分,但如果你決定走這條路,你可以訂閱的形式提交事件和重寫的網址:

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

哦!當然!謝謝。我創建了兩個操作方法(HttpGet和HttpPost),並使用RedirectToAction從HttpPost方法到HttpGet方法。它工作正常。謝謝! – greatromul

0

就你所說要將表格發佈到Html.BeginForm("Test", "Test")而言,你總是會回到同一頁面。

一個解決辦法是使用「RedirectToAction」(鑑於)使用顯式重定向到動作,或者你可以使用JavaScript來改變形式的行動:

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

我超級遲到了,但只是想發佈解決方案以供參考。讓我們假設這個表單不僅僅是一個強大的輸入。假設還有其他輸入,我們可以將表單的輸入封裝到我們模型中的類中,稱爲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 
     } 

    }