2016-01-11 32 views
2

我正在用ASP.NET MVC 4和C#創建一個站點。主頁面是一個帶有「搜索」標籤的提交按鈕的搜索欄。我希望用戶能夠輸入音樂藝術家並按下「搜索」按鈕。然後該網站應該帶着結果進入「結果」頁面。如何在按下提交按鈕後重定向到下一頁?

按下搜索按鈕後,我無法進入結果頁面。

我視圖Index.cshtml形式如下:

<form method="post" class="form-inline"> 
    <div class="row"> 
     <div class="col-md-1" style="min-width:300px"> 
      <input type="text" name="Artist" class="form-control box-shadow--4dp" placeholder="Artist Name" /> 
     </div> 
     <div class="col-md-2"> 
      <input type="submit" class="btn btn-default box-shadow--4dp" value="Search" /> 
     </div> 
    </div> 
</form> 

而我HomeController.cs類似於:

namespace Task2.Controllers 
{ 
    public class HomeController : Controller 
    { 
     public ActionResult Index() 
     { 
      return View(); 
     } 

     // edit 
     [HttpPost] 
     public ActionResult Index(string Artist) 
     { 
      return RedirectToAction("Result", "Home"); 
     } 

     public ActionResult Contact() 
     { 
      ViewBag.Message = "For more information you can contact me using the form below."; 

      return View(); 
     } 

     public ActionResult Result(string Artist) 
     { 
      ViewBag.Message = Artist; 
      return View(); 
     } 
    } 
} 

所以總結,哪能引起提交按鈕重定向用戶到結果頁面的結果?

謝謝!

+1

[執行提交(回發)中並用ASP.net MVC重定向](的可能的複製http://stackoverflow.com/questions/9978348/performing-submitpostback-and-redirect-with-asp-net- mvc) –

回答

3

如果您希望將輸入作爲查詢字符串,那麼只需將您的表單方法更改爲GET即可。它會將輸入作爲查詢字符串重定向到結果頁面。

@using (Html.BeginForm("Result","Home",FormMethod.Get,new {@class= "form-inline" })) 
{ 
    <div class="row"> 
     <div class="col-md-1" style="min-width:300px"> 
      <input type="text" name="Artist" class="form-control box-shadow--4dp" placeholder="Artist Name" /> 
     </div> 
     <div class="col-md-2"> 
      <input type="submit" class="btn btn-default box-shadow--4dp" value="Search" /> 
     </div> 
    </div> 
} 
+0

這工作。非常感謝你。 – zachboy82

3

您的HTML目前的設置方式是,您的表單將張貼到控制器的Index方法中。

要進行重定向,你可以這樣做:

[HttpPost] 
public ActionResult Index(string searchTerm) 
{ 
    //handle your search stuff here... 
    return RedirectToAction("Results", "Home"); 
} 

但是,你可以用你的當前形式在HTML.BeginForm和發佈比指數方法等具體行動方法 - 也許是一個搜索操作方法然後將重定向到結果,例如傳遞結果集合。

+0

用您所說的版本更新我的代碼。它不會進入結果頁面。 – zachboy82

相關問題