2016-12-24 37 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

相关问题