2014-02-28 51 views
0

我有一個簡單的形式,看起來像這樣:Html.BeginForm不攜帶其當前PARAMS

@using (Html.BeginForm("search", "home", new { param1 = "value1" }, FormMethod.Get)) 
{ 
    @Html.TextBox("Search", ViewBag.Search as string) 
    <button type="submit">Search </button> 
} 

HTML輸出如下:

<form action="/home/search?param1=value1" method="get"> 
    <input id="Search" name="Search" type="text" value=""> 
    <button type="submit">Search </button> 
</form> 

和我的控制器看起來是這樣的:

public ActionResult Search(string param1, string search) 
{ 
    // param1 returns as "null" 
    // search contains the value that was inside the textbox 
} 

有人知道我做錯了什麼?

+2

您可以爲'param1'創建'hidden-field' –

+0

難題... t hanks! –

回答

0

Selman22建議正確的方法來完成這一點。不要將參數放在實際的URL上,而是將它們放在隱藏的窗體中。

@using (Html.BeginForm("search", "home", null, FormMethod.Get)) 
{ 
    <input type="hidden" name="param1" value="@ViewBag.Param1Value.ToString()" /> 
    @Html.TextBox("Search", ViewBag.Search as string) 
    <button type="submit">Search </button> 
} 

謝謝!!!!

+1

也可以使用[Html.Hidden](http://msdn.microsoft.com/en-us/library/gg569498(v = vs.111).aspx)幫助程序方法。 :) –

1

一對夫婦的建議

  • 用你的形式與POST
  • 我總是建議使用強類型的視圖模型,它有很多好處

所以,你的代碼變得:

public class SearchViewModel { 
    public string param1 {get;set;} 
    public string search {get;set;} 
} 

[HttpPost] // <-- were you missing this before? 
public ActionResult Search(SearchViewModel model) 
{ 
    // access with model.param1 
} 

@model SearchViewModel 

@using (Html.BeginForm("search", "home", FormMethod.POST)) 
{ 
    @Html.HiddenFor(x=>x.param1) 
    @Html.TextBoxFor(x=>x.search) 
    <button type="submit">Search </button> 
}