我有一个与IEnumerable<ProductCategoryViewModel>
绑定的视图
在此视图中,有一个下拉框,其值为搜索类型值,因此我可以按代码或名称搜索产品类别。
这是控制器:
public ActionResult Index()
{
List<SelectListItem> list = new List<SelectListItem> {
new SelectListItem {Text="By Code", Value="1", Selected=true},
new SelectListItem {Text="By Name", Value="2"}
};
var categories = _db.mt_ProductCategories
.Select(
p => new ProductCategoriesViewModel
{
Id = p.Id,
Name = p.CatName,
CatCode = p.CatCode, SearchTypes=list
});
if (Request.IsAjaxRequest())
{
return PartialView("_ProductCategoryList", categories);
}
return View(categories);
}
这是 ViewModel
public class ProductCategoriesViewModel
{
public int Id { get; set; }
public string CatCode { get; set; }
public string Name { get; set; }
public IEnumerable<SelectListItem> SearchTypes { get; set; }
public string SearchType { get; set; }
}
这是查看
@model IEnumerable<eComm1.Models.ProductCategoriesViewModel>
@using (Ajax.BeginForm("Search", "ProductCategory",
new AjaxOptions
{
HttpMethod = "POST",
UpdateTargetId = "prod-grid",
InsertionMode = InsertionMode.Replace,
OnSuccess = "loaddivdata"
}))
{
//i need to put the drop down here but since i passed a collection it does not show the property "SearchType". the code should be like below but errors
@Html.DropDownListFor(m=>m.SearchType, Model.SearchTypes)
}
如何在当前视图中访问属性SearchType?
答案 0 :(得分:2)
您需要一个具有SearchType
和SearchType
属性的视图模型,并且在视图中使用该视图模型的单个实例(并且最初通过调用{生成ProductCategories
的列表{1}})。
@Html.Action()
并在控制器中
public class ProductSearchVM
{
public string searchText { get; set; }
public string SearchType { get; set; }
public IEnumerable<SelectListItem> SearchTypes { get; set; }
}
并在视图中
public ActionResult Index()
{
ProductSearchVM model = new ProductSearchVM
{
SearchType = "1", // this is how you set the selected value
SearchTypes = new List<SelectListItem>
{
new SelectListItem { Text = "By Code", Value = "1" }, // no point adding Selected = true; - its ignored by the HtmlHelper
new SelectListItem { Text = "By Name", Value = "2" }
}
};
return View(model)
}