您可以使用视图模型:
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
显示搜索结果的部分:
@model string
<div>
@Html.DisplayForModel()
</div>
然后,如果您想在下拉列表选择更改时在文本框中显示选定的员工姓名,您可以使用 jQuery 并订阅.change()
此下拉列表的事件。因此,在单独的 javascript 中,我们可以输入以下内容:
$(function() {
$('#employeesDdl').change(function() {
var employeeName = $('option:selected', this).text();
$('#EmployeeName').val(employeeName);
});
});