2016-12-24 38 views
-1

我在我的MVC5客戶模型的索引視圖中創建了一個搜索欄,其中有兩個單選按鈕。我想將搜索欄的內容傳遞給我的CustomersController,即已經選擇了哪個單選按鈕以及在搜索欄中輸入了哪些內容。然而,控制器並沒有「看到」視圖中的名稱。我究竟做錯了什麼?在索引視圖如何將視圖中的搜索欄內容綁定到控制器MVC

搜索條碼:

@using (Html.BeginForm("Index", "CustomersController", FormMethod.Get)) 
{ 
    <b>Search by:</b>@Html.RadioButton("searchBy", "Company")<text> Company</text> 
    @Html.RadioButton("searchBy", "Last Name")<text>Last Name</text><br /> 
    @Html.TextBox("Search");<input type="submit" value="Search" /> 
} 

指數的ActionResult在CustomersController:

public ActionResult Index() 
{ 
    if (searchBy == "Company") 
    { 
     return View(db.Customers 
      .Where(x => x.Company.Contains == Search || Search == null).ToList()); 
    } 
    else 
    { 
     return View(db.Customers.Where(x => x.LastName.StartsWith(Search)).ToList()); 
    } 
} 

任何幫助將非常感激。謝謝。

+0

你正在使用'GET'爲什麼沒有PARAM參考'索引'方法?它應該是'Index(string searchBy)'。那麼你從哪裏獲得'searchBy'? –

回答

0

更改您的Razor視圖下面你不需要申請您的全控制器的名稱只是通過「客戶」

@using (Html.BeginForm("Index", "Customers", FormMethod.Get)) 
    { 
     <b>Search by:</b>@Html.RadioButton("searchBy", "Company")<text> Company</text> 
     @Html.RadioButton("searchBy", "Last Name")<text>Last Name</text><br /> 
     @Html.TextBox("Search");<input type="submit" value="Search" /> 
    } 

你的控制器方法如下傳遞兩個參數像下面

public ActionResult Index(string searchby,string Search) 
    { 

     if (searchby == "Company") 
     { 
      return View(db.Customers.Where(x => x.Company.Contains == Search || Search == null).ToList()); 
     } 
     else 
     { 
      return View(db.Customers.Where(x => x.LastName.StartsWith(Search)).ToList()); 
     } 
    } 

希望它可以幫助..

+0

我在「搜索」下仍然會看到紅色的曲線。爲什麼? –

+0

你有沒有傳過兩個參數?如果是,請確保你在參數和你已經使用該參數的地方拼寫正確。 字符串搜索, 字符串搜索 有兩個參數,你必須通過,因爲我在我的答案中提到。 – Curiousdev

+0

在那裏你會發現紅色的小方格將你的光標移動到那裏,然後按** Cntrl +空格**它會給你一個提示你做錯了什麼,以及如何糾正.. – Curiousdev

相關問題