ビューモデルを使用できます:
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);
});
});