。
在这个问题中,您需要通过下拉框的onchange事件来获取数据库中的字符串数据,并通过ajax将数据返回到页面上。以下是一个示例代码,演示了如何使用.net控制器类来实现这个功能:
前端代码(HTML):
<select id="myDropdown" onchange="getData()">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
</select>
<div id="result"></div>
<script>
function getData() {
var selectedValue = document.getElementById("myDropdown").value;
// 发送ajax请求
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
document.getElementById("result").innerHTML = xhr.responseText;
}
};
xhr.open("GET", "/Controller/GetData?selectedValue=" + selectedValue, true);
xhr.send();
}
</script>
后端代码(.NET控制器类):
public class Controller : ApiController
{
[HttpGet]
public string GetData(string selectedValue)
{
// 在这里根据selectedValue从数据库中获取数据
// 假设数据库连接字符串为connectionString
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlCommand command = new SqlCommand("SELECT Data FROM MyTable WHERE Value = @selectedValue", connection);
command.Parameters.AddWithValue("@selectedValue", selectedValue);
SqlDataReader reader = command.ExecuteReader();
if (reader.Read())
{
return reader["Data"].ToString();
}
else
{
return "No data found";
}
}
}
}
上述代码中,前端部分使用了一个下拉框,并通过onchange事件触发getData()函数。该函数获取选中的值,并使用ajax发送GET请求到后端的GetData方法。后端控制器类中的GetData方法接收selectedValue参数,并根据该值从数据库中获取相应的数据。最后,将数据作为字符串返回给前端页面。
请注意,上述代码仅为示例,实际情况中需要根据您的具体需求进行适当的修改和优化。此外,您还需要在.net项目中配置数据库连接字符串,并确保数据库中存在相应的表和数据。
推荐的腾讯云相关产品和产品介绍链接地址:
领取专属 10元无门槛券
手把手带您无忧上云