我希望我的用户在下拉框中选择一个项目,一旦选中,我希望选中与此值相关联的其他字段来填充文本框。当您更改下拉列表中的值时,文本框中的记录会更改。
例如,如果您选择customerId为1001,则FirstName,LastName和EmailAddress协同为1001应填充3个字段的文本框。 CustomerId =&#34; 1001&#34;,FirstName =&#34; John&#34;,LastName =&#34; Travolta&#34;,EmailAddress =&#34; John.Travolta@yahoo.com" < / p>
这是控制器代码
public class HomeController : Controller
{
public ActionResult Index()
{
var list = new SelectList(new[]
{
new { ID = "1", Name = "Select Id" },
new { ID = "2", Name = "1001" },
new { ID = "3", Name = "1002" },
new { ID = "4", Name = "1003" },
},
"ID", "Name", 1);
ViewData["list"] = list;
return View();
}
public List<Customer> GetCustomerById(String CustomerId)
{
var objCustomer = new List<Customer>();
objCustomer.Add(new Customer {CustomerId="1001", FirstName="John", LastName="Travolta", EmailAddress="John.Travolta@yahoo.com"});
objCustomer.Add(new Customer {CustomerId = "1002", FirstName = "Bayo", LastName = "Adenuga", EmailAddress = "Bayo.Adenuga@yahoo.com" });
objCustomer.Add(new Customer { CustomerId = "1003", FirstName = "Feyi", LastName = "Olawoye", EmailAddress = "feyi.olawoye@yahoo.com" });
var objResult = from c in objCustomer
where c.CustomerId == CustomerId
select c;
return objResult.ToList();
}
[HttpPost]
public ActionResult Action(string customerId)
{
var results = GetCustomerById(customerId);
return Json(results);
}
}
以下是我的视图代码
@model DropdownSelectedFillTextBox.Models.Customer
@{
ViewBag.Title = "Home Page";
}
<script src="//ajax.aspnetcdn.com/ajax/jQuery/jquery-1.9.1.min.js">
</script>
@using (@Html.BeginForm("Action","Home",FormMethod.Post))
{
<h2>Dotuns Test</h2>
<div>
@Html.DropDownList("drpList",ViewData["list"] as SelectList)
</div>
<div>First Name</div>
<div>
@Html.TextBox("FirstName", null, new { @class = "form-control" })
</div>
<div>Last Name</div>
<div>
@Html.TextBox("LastName", null, new { @class = "form-control" })
</div>
<div>Email Address</div>
<div>
@Html.TextBox("EmailAddress", null, new { @class = "form-control" })
</div>
}
<script type="text/javascript">
function Action(customerId) {
$.ajax({
url: '@Url.Action("Action", "Home")',
type: "POST",
data: { "customerId": customerId },
"success": function (data) {
if (data != null) {
var vdata = data;
$("#FirstName").val(vdata[0].FirstName);
$("#LastName").val(vdata[0].LastName);
$("#EmailAddress").val(vdata[0].EmailAddress);
}
}
});
}
</script>
我将jquery更改为下面的代码。我在那里放了一个警报框,但是它已经被击中但没有任何事情发生。当我在控制器中的方法上设置断点时。它没有达到突破点。
<script type="text/javascript">
$('#drpList').change(function () {
alert("Hello Test");
$.ajax({
url: '@Url.Action("Action", "Home")',
type: "POST",
data: { "customerId": customerId },
"success": function (data) {
if (data != null) {
var vdata = data;
$("#FirstName").val(vdata[0].FirstName);
$("#LastName").val(vdata[0].LastName);
$("#EmailAddress").val(vdata[0].EmailAddress);
}
}
});
});
</script>