真的需要帮助。
我为我的网络应用程序设置了搜索功能,但下拉列表列表不起作用。每当我点击"搜索" DropDownList 会恢复为默认值("全部")并且它在搜索中没有扮演任何角色......
这是我的控制器代码和搜索调用的方法: 稍后会有View部分的代码
public ActionResult Index(string title = "", string city = "")
{
var listOfCities = new List<string>();
var genreQry = from d in db.Restaurants
orderby d.City
select d.City;
listOfCities.AddRange(genreQry.Distinct());
ViewBag.citiesList= new SelectList(listOfCities);
var restaurants = from m in db.Restaurants
select m;
if (!string.IsNullOrEmpty(city))
{
restaurants = restaurants.Where(s => s.City.Contains(city));
}
if (!string.IsNullOrEmpty(title))
{
restaurants = restaurants.Where(x => x.RestaurantName == title);
}
return View(restaurants);
}
来自视图的代码:
@model IEnumerable<RestaurantsInLithuania.Models.Restaurant>
....
@using (Html.BeginForm("Index", "Restaurants", FormMethod.Get))
{
City: @Html.DropDownList("citiesList", "All")
Title: @Html.TextBox("title") <br />
<input type="submit" value="Filter" class="whatever" />
}
<table class="table">
<tr>
<th>@Html.DisplayNameFor(model => model.RestaurantName)</th>
....
</tr>
@foreach (var item in Model)
{
<tr>
<td>@Html.DisplayFor(modelItem => item.RestaurantName)</td>
<td>@Html.DisplayFor(modelItem => item.City)</td>
<td>@Html.DisplayFor(modelItem => item.TypeOfCuisine)</td>
<td></td>
</tr>
}
</table>
答案 0 :(得分:0)
您的下拉列表的值在搜索中不起任何作用,因为它具有name="citiesList"
属性,但您方法中的参数名为city
。如果将属性更改为string citiesList
,则其值将绑定到所选选项的值。
但是,当您返回视图时,下拉列表中的所选选项仍为"All"
,因为您没有绑定任何内容。
创建视图模型以在视图中表示您想要的内容
public class RestaurantVM
{
public string Title { get; set; }
public string City { get; set; }
public IEnumerable<SelectListItem> CityList { get; set; }
public IEnumerable<Restaurant> Restaurants { get; set; }
}
然后在控制器方法
中public ActionResult Index(string title, string city)
{
var restaurants = from m in db.Restaurants select m;
if (!string.IsNullOrEmpty(city))
{
restaurants = restaurants.Where(s => s.City.Contains(city));
}
if (!string.IsNullOrEmpty(title))
{
restaurants = restaurants.Where(x => x.RestaurantName == title);
}
var cities = db.Restaurants.OrderBy(x => x.City).Select(x => x.City).Distinct();
RestaurantVM model = new RestaurantVM()
{
Title = title,
City = city,
CityList = new SelectList(cities),
Restaurants = restaurants
};
return View(model );
}
然后在视图中
@model yourAssembly.RestaurantVM
....
@using (Html.BeginForm("Index", "Restaurants", FormMethod.Get))
{
@Html.LabelFor(m => m.City)
@Html.DropDownListFor(m => m.City, Model.CityList, "All")
@Html.LabelFor(m => m.Title)
@Html.TextBoxFor(m => m.Title)
<input type="submit" value="Filter" class="whatever" />
}
<table class="table">
<thead>
<tr>
<th>@Html.DisplayNameFor(m => m.Restaurants.FirstOrDefault().RestaurantName)</th>
....
</tr>
</thead>
<tbody>
@foreach (var item in Model.Restaurants)
{
<tr>
<td>@Html.DisplayFor(m => item.RestaurantName)</td>
<td>@Html.DisplayFor(m => item.City)</td>
<td>@Html.DisplayFor(m => item.TypeOfCuisine)</td>
<td></td>
</tr>
}
</tbody>
</table>