你可以使用一个视图模型:
public class SearchViewModel
{
// property used to represent the selected employee id in the dropdown
[DisplayName("Employee")]
public string SelectedEmployeeId { get; set; }
// property used to hold the list of employees shown in the dropdown
public IEnumerable<SelectListItem> Employees { get; set; }
// property used for the textbox
[DisplayName("Name")]
public string EmployeeName { get; set; }
// property that will be populated after submitting the form
// and contain the search results. I am using string for the
// purpose of the demonstration but could be any arbitrary complex
// view model depending on what your results contain
public string SearchResult { get; set; }
}
然后控制器:
public class HomeController: Controller
{
public ActionResult Index()
{
var model = new SearchViewModel
{
Employees = db.Employees.ToList().Select(e => new SelectListItem
{
Value = e.EmployeeId,
Text = e.Name
})
};
return View(model);
}
[HttpPost]
public ActionResult Index(SearchViewModel model)
{
// at this stage we have the SelectedEmployeeId and SomeValue
// properties passed => we do the search and set the results:
model.SearchResult = "this is the result of your search";
// we repopulate the Employees collection because only the selected
// employee id was passed when the form was submitted
model.Employees = db.Employees.ToList().Select(e => new SelectListItem
{
Value = e.EmployeeId,
Text = e.Name
});
// we redisplay the view
return View(model);
}
}
接下来,我们可以有一个~/Views/Home/Index.cshtml
观点:
@model SearchViewModel
@using (Html.BeginForm())
{
<div>
@Html.LabelFor(x => x.SelectedEmployeeId)
@Html.DropDownListFor(
x => x.SelectedEmployeeId,
Model.Employees,
new { id = "employeesDdl" }
)
</div>
<div>
@Html.LabelFor(x => x.EmployeeName)
@Html.EditorFor(x => x.EmployeeName)
</div>
<button type="submit">Search</button>
}
<div id="results">
@if (Model.SearchResult != null)
{
@Html.Partial("_Result", Model.SearchResult)
}
</div>
接下来,我们定义了一个~/Views/Home/_Result.cshtml
部分将显示搜索结果:如果你想在文本框中显示所选员工的姓名时,下拉列表选择改变,你可以使用jQuery和订阅
@model string
<div>
@Html.DisplayForModel()
</div>
然后到此下拉菜单的.change()
事件。因此,在一个单独的JavaScript,我们可以把下面的:
$(function() {
$('#employeesDdl').change(function() {
var employeeName = $('option:selected', this).text();
$('#EmployeeName').val(employeeName);
});
});
也许我错过读您的解决方案,但我觉得OP正在寻求改变根据所选项目dropdownlists搜索条件。即下拉标签将是“按......搜索”,例如下拉列表将包含字符串文字“EmployeeName”,“EmployeeId”。然后,如果选择了EmployeeName,则用户应该输入“Mary”,如果选择了EmployeeId,则应该输入“0099”。 – 2012-07-10 08:17:43
@ mouters,也许你是对的。我可能不明白OP在问什么。 – 2012-07-10 08:25:26