Sah*_*tty 4 c# asp.net-mvc asp.net-mvc-3
我有两个表,即州和国家.这两个是我的视图页面中的下拉列表.我正在使用独立查询显示每个下拉值.在表状态中我有stateid和countryid.我需要根据国家/地区选择过滤州的值.我甚至有一个名为Table的主表,它由状态和国家的ID组成.以下是我用来显示的方式,
enter code here
Run Code Online (Sandbox Code Playgroud)
//获取状态值
var query = (from i in dbContext.countries
join j in dbContext.States on i.Country_id equals j.Country_id
where j.State_id >= 0
select new
{
state = j.State_name}).ToArray//To get state values
Run Code Online (Sandbox Code Playgroud)
在此处输入代码
var str = (from li in dbContext.countries
where li.Country_id >= 1
select new
{
country = li.Country_name}).ToArray();//To get country
Run Code Online (Sandbox Code Playgroud)
值
我怎么能查询过滤主表"table"中的值.我在编写查询过滤时遇到问题这是否可以使用linq查询?请建议我如何做到这一点谢谢
Jor*_*rge 14
这可以通过不同方式实现.一种方法是让服务器在第一个下拉列表更改时通过Ajax返回已过滤的有效选项列表.
例如,假设这种情况:带有两个DropDownLists的视图; 一个与国家,另一个与国家.具有状态的DropDownList默认为空并在默认情况下禁用,直到选择国家/地区为止.
所以你可以在你的控制器中使用这个Action:
public ActionResult Index()
{
ViewBag.Country = new [] {
new SelectListItem() { Text = "Venezuela", Value = "1" },
new SelectListItem() { Text = "United States", Value = "2" }
};
return View();
}
Run Code Online (Sandbox Code Playgroud)
而这个观点:
<div class="editor-field">
@Html.DropDownList("Country")
@Html.DropDownList("State", Enumerable.Empty<SelectListItem>(), "States", new { @disabled = "disabled" })
</div>
Run Code Online (Sandbox Code Playgroud)
现在在控制器中添加POST操作.它接收所选国家/地区的ID并返回包含已过滤状态列表的JSON:
[HttpPost]
public ActionResult StatesByCountry(int countryId)
{
// Filter the states by country. For example:
var states = (from s in dbContext.States
where s.CountryId == countryId
select new
{
id = s.Id,
state = s.Name
}).ToArray();
return Json(states);
}
Run Code Online (Sandbox Code Playgroud)
最后一件事是客户端代码.此示例使用jQuery并在country下拉列表上设置更改事件侦听器,该下拉列表通过Ajax调用新的控制器操作.然后,它使用返回的值来更新"State"DropDownList.
$(document).ready(function () {
$('#Country').change(function () {
$.ajax({
url: '/Home/StatesByCountry',
type: 'POST',
data: { countryId: $(this).val() },
datatype: 'json',
success: function (data) {
var options = '';
$.each(data, function () {
options += '<option value="' + this.id + '">' + this.state + '</option>';
});
$('#State').prop('disabled', false).html(options);
}
});
});
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9616 次 |
| 最近记录: |