Несколько столов с несколькими выпадающими меню
1) Добавьте два раскрывающихся списка на главном экране, как
<div class="dropdown">
@Html.DropDownList("id", (List<SelectListItem>)ViewBag.proj, "--Select id--", new { @onchange = "CallChangefunc1(this.value)" })
</div>
<div class="dropdown">
@Html.DropDownList("id", (List<SelectListItem>)ViewBag.funds, "--Select id--", new { @onchange = "CallChangefunc2(this.value)" })
</div>
2) Добавить два частичных вида 1-го с именем _GetProjectCategory.cshtml
и 2-го с именем _GetFundCategory.cshtml
Убедитесь, что
1-й частичный вид @model
будет иметь тип @model IEnumerable<WebApplicationMVC1.Controllers.ProjectCategory>
2-й частичный вид @model
будет иметь тип @model IEnumerable<WebApplicationMVC1.Controllers.FundCategory>
Просто добавьте свой контент в соответствующем частичном представлении.
Убедитесь, что оба ваших частичных представления содержат.
@foreach (var item in Model) { //You table contents }
3) Назовите оба частичных вида на главном экране как
<div id="myPartialView1">
@{Html.RenderPartial("_GetProjectCategory", Model.ProjectCategories);}
</div>
<div id="myPartialView2">
@{Html.RenderPartial("_GetFundCategory", Model.FundCategories);}
</div>
4) Затем создайте модель вида, подобную
public class ProjectFundViewModel
{
public List<ProjectCategory> ProjectCategories { get; set; }
public List<FundCategory> FundCategories { get; set; }
}
5) Ваш метод действия будет (его пример кода и заменить вашим кодом).
public ActionResult Index()
{
//The below query replace by yours
var projects = db.ProjectCategories.ToList();
List<SelectListItem> dropDownItems1 = projects.Select(c => new SelectListItem { Text = c.title, Value = c.id.ToString() }).ToList();
ViewBag.proj = dropDownItems1;
//The below query replace by yours
var funds = db.FundCategories.ToList();
List<SelectListItem> dropDownItems2 = funds.Select(c => new SelectListItem { Text = c.title, Value = c.id.ToString() }).ToList();
ViewBag.funds = dropDownItems2;
ProjectFundViewModel viewModel = new ProjectFundViewModel
{
ProjectCategories = projects,
FundCategories = funds
};
return View(viewModel);
}
6) Добавить вызов ajax на ваш основной вид, который вызывается при изменении любого параметра в соответствующем раскрывающемся списке
<script>
function CallChangefunc1(id) {
$.ajax({
url: "@Url.Action("GetProjectCategory", "Default")",
data: { id: id },
type: "Get",
dataType: "html",
success: function (data) {
console.log(data);
//Whatever result you have got from your controller with html partial view replace with a specific html.
$("#myPartialView1").html( data ); // HTML DOM replace
}
});
}
function CallChangefunc2(id) {
$.ajax({
url: "@Url.Action("GetFundCategory", "Default")",
data: { id: id },
type: "Get",
dataType: "html",
success: function (data) {
console.log(data);
//Whatever result you have got from your controller with html partial view replace with a specific html.
$("#myPartialView2").html( data ); // HTML DOM replace
}
});
}
</script>
7) И, наконец, ваш вызов ajax попал под метод действия, который может отобразить соответствующее частичное представление.
public PartialViewResult GetProjectCategory(int id)
{
var projects = db.ProjectCategories.ToList();
var model = projects.Where(x => x.id == id).ToList();
return PartialView("_GetProjectCategory", model);
}
public PartialViewResult GetFundCategory(int id)
{
var funds = db.FundCategories.ToList();
var model = funds.Where(x => x.id == id).ToList();
return PartialView("_GetFundCategory", model);
}
8) Убедитесь, что ваш основной вид @model
равен @model WebApplicationMVC1.Controllers.ProjectFundViewModel
, а не IEnumerable
.
Один стол с несколькими выпадающими меню
1) Добавьте два выпадающих в главном окне с идентификатором
<div class="dropdown">
@Html.DropDownList("id", (List<SelectListItem>)ViewBag.ids, "--Select id--", new { @onchange = "CallChangefunc1(this.value)", @id = "dropdown1" })
</div>
<div class="dropdown">
@Html.DropDownList("title", (List<SelectListItem>)ViewBag.titles, "--Select title--", new { @onchange = "CallChangefunc2(this.value)", @id = "dropdown2" })
</div>
2) Добавить частичный вид с именем GetFilteredData.cshtml
с моделью @model IEnumerable<WebApplicationMVC1.Controllers.ProjectCategory>
.
Убедитесь, что ваш частичный вид содержит.
@foreach (var item in Model) { //You table contents }
3) Назовите свой частичный вид на главном экране как
<div id="myPartialView">
@{Html.RenderPartial("GetFilteredData", Model.ProjectCategories);}
</div>
4) Теперь ваш первый раскрывающийся список содержит ids
, а второй - titles
из категории проектов.
public ActionResult Index()
{
var projects = db.ProjectCategories.ToList();
List<SelectListItem> dropDownItems1 = projects.Select(c => new SelectListItem { Text = c.id.ToString(), Value = c.id.ToString() }).ToList();
ViewBag.ids = dropDownItems1;
List<SelectListItem> dropDownItems2 = projects.Select(c => new SelectListItem { Text = c.title, Value = c.title }).ToList();
ViewBag.titles = dropDownItems2;
ProjectFundViewModel viewModel = new ProjectFundViewModel
{
ProjectCategories = projects,
};
return View(viewModel);
}
5) Добавить вызов ajax из основного вида, как
<script>
function CallChangefunc1(id) {
var title = $("#dropdown2").val();
$.ajax({
url: "@Url.Action("GetFilteredData", "Default2")",
data: { id: id, title: title },
type: "Get",
dataType: "html",
success: function (data) {
console.log(data);
//Whatever result you have got from your controller with html partial view replace with a specific html.
$("#myPartialView").html( data ); // HTML DOM replace
}
});
}
function CallChangefunc2(title) {
var id = $("#dropdown1").val();
$.ajax({
url: "@Url.Action("GetFilteredData", "Default2")",
data: { id: id, title: title },
type: "Get",
dataType: "html",
success: function (data) {
console.log(data);
//Whatever result you have got from your controller with html partial view replace with a specific html.
$("#myPartialView").html( data ); // HTML DOM replace
}
});
}
</script>
6) И, наконец, ваш ajax-вызов достиг метода ниже действия с 2 параметрами.
public PartialViewResult GetFilteredData(int? id, string title)
{
var query = db.ProjectCategories.ToList();
if (id != null)
query = query.Where(x => x.id == id).ToList();
if (!string.IsNullOrEmpty(title))
query = query.Where(x => x.title == title).ToList();
return PartialView("GetFilteredData", query);
}