在DropDownList选择中,使用Ajax Partial View过滤SQL查询,MVC

时间:2017-02-25 02:39:34

标签: c# sql ajax asp.net-mvc

我不知道在哪里,最好的做法是从下拉列表中过滤所选的值。所以这里:

在下拉列表选择中,我希望所选值过滤sql查询,并仅显示与下拉列表选择的ID相关的视频。目前它只显示数据库中的第一个视频10次。数据库中有10个视频我意识到因为ID = ID它们都在显示...我只想在下拉列表中与选定项目相关的那些视频在局部视图中显示。

视图模型

using System.Web.Mvc;
using System.Collections.Generic;

namespace ACGteam.ViewModels
{
    public class AthleteVideoViewModel
    {
        public List<AthleteVideoViewModel> AthleteDbList { get; set; }
        public int anAthleteID { get; set; }
        public int AthleteID { get; set; }
        public string AthleteName { get; set; }
        public int AthleteVideoID { get; set; }
        public string AthleteVideo { get; set; }
        public IEnumerable<SelectListItem> AthleteListItems
        {
            get { return new SelectList(AthleteDbList, "AthleteID", "AthleteName"); }
        }
        public IEnumerable<SelectListItem> AthleteVideosList
        {
            get { return new SelectList(AthleteDbList, "anAthleteID", "AthleteVideo"); }
        }
    }
}

CONTROLLER

using System;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Collections.Generic;
using ACGteam.Models;
using ACGteam.ViewModels;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;
using ACGteam.Services;
using System.Web.UI.WebControls;
using System.Data.Entity.Infrastructure;


namespace ACGteam.Controllers
{
    public class VideosController : Controller
    {
        public ActionResult VideoPage()
        {
            return View();
        }

        public ActionResult VideoPage2016()
        {
            var ddlAthleteSelected = new AthleteVideoViewModel();

            ddlAthleteSelected.AthleteDbList = PopulateAthleteNames();

            return View(ddlAthleteSelected);
        }
        private List<AthleteVideoViewModel> PopulateAthleteNames()
        {
            using (SqlConnection connection = new SqlConnection(DatabaseConnection.GetConnectionString("acgvideodbConnectionString")))
            {
                using (SqlCommand cmd = connection.CreateCommand())
                {
                    try
                    {
                        cmd.CommandText = "SELECT AthleteID, AthleteName AS Athlete FROM Athlete_Name ORDER BY Athlete";
                        using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
                        {
                            DataSet ds = new DataSet();
                            sda.Fill(ds);

                            var items = ds.Tables[0].AsEnumerable().Select(dataRow => new AthleteVideoViewModel { AthleteID = dataRow.Field<int>("AthleteID"), AthleteName = dataRow.Field<string>("Athlete") }).ToList();

                            return items;
                        }
                    }
                    finally
                    {

                    }
                }
            }
        }
        public PartialViewResult GetAthleteVideo(int AthleteID)
        {

            var vidModels = new AthleteVideoViewModel();
            vidModels.AthleteDbList = PopulateVideosWithAthleteID();
            var vid = vidModels.AthleteDbList.Where(a => a.anAthleteID == AthleteID).FirstOrDefault();

            vidModels.AthleteVideo = vid.AthleteVideo;

            return PartialView("_ShowAthlete", vidModels);
        }

        private List<AthleteVideoViewModel> PopulateVideosWithAthleteID()
        {

            using (SqlConnection connection = new SqlConnection(DatabaseConnection.GetConnectionString("acgvideodbConnectionString")))
            {
                using (SqlCommand cmd = connection.CreateCommand())
                {
                    try
                    {
                        List<AthleteVideoViewModel> vidmod = new List<AthleteVideoViewModel>();
                        cmd.CommandText = "SELECT Athlete_Name.AthleteID AS AthleteID, Athlete_Video.anAthleteID AS anAthleteID, Athlete_Video.AthleteVideo AS AthleteVideo FROM Athlete_Video INNER JOIN Athlete_Name ON Athlete_Name.AthleteID = Athlete_Video.anAthleteID";
                        SqlDataAdapter sda = new SqlDataAdapter(cmd);
                        DataSet ds = new DataSet();
                        sda.Fill(ds);
                        DataTable dt = new DataTable();
                        ds.Tables.Add(dt);
                        vidmod = ds.Tables[0].AsEnumerable().Select(dataRow => new AthleteVideoViewModel { AthleteID = dataRow.Field<int>("AthleteID"), anAthleteID = dataRow.Field<int>("anAthleteID"), AthleteVideo = dataRow.Field<string>("AthleteVideo") }).ToList();

                        return vidmod;
                    }
                    finally
                    {
                    }
                }
            }
        }
    }
} 

主要观点

@model ACGteam.ViewModels.AthleteVideoViewModel
@{
    ViewBag.Title = "VideosPage2016";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="container">
    <div class="box">
        <h2 style="text-align:center">ACG 2015-2016 Competition Season</h2>
        <h2 style="text-align:center"> Athlete Videos </h2>
        <div class="row">
            <div class="col-lg-12" style="margin:auto 0; display:block">
                @Html.DropDownListFor(m => m.AthleteID, Model.AthleteListItems, new { Class = "imgcenter", id = "ddlAthlete" })
            </div>
        </div>

        <div id="partialDiv">
            @Html.Partial("_ShowAthlete")
        </div>

        <script>
            $(document).ready(function () {
                $("#ddlAthlete").on("change", function () {
                    $.ajax(
                    {
                        url: "GetAthleteVideo?AthleteID=" + $(this).prop("value"),
                        type: "GET",
                        data: "",
                        contentType: "application/json; charset=utf-8",
                        success: function (data)
                        {
                            $("#partialDiv").html(data);
                        },
                        error: function () { alert("error"); }
                    });
                });
            });
        </script>

部分视图

@model ACGteam.ViewModels.AthleteVideoViewModel
@{
    ViewBag.Title = "_ShowAthlete";
}
<div class="row">
    <div style="display: block; text-align: center;">
        <div>
            <img height="75" width="100" src="/Img/AvantCoeurLogoGirls.png" />
        </div>
        <div class="col-md-12 display-label">
            @Html.DisplayFor(items => items.AthleteName)
        </div>

        <div class="box">
            <div class="row">
                    @foreach (var athVid in Model.AthleteDbList)
                {
                        <div class="col-md-6 col-lg-4 img-responsive">
                            <video style="height:250px; width:250px" controls="controls">
                                <source src="@Html.DisplayFor(vidmod => vidmod.AthleteVideo)" type="video/mp4" />
                            </video>
                            <br />
                            <strong>GroupShow_Candyland</strong>
                        </div>
                }

This is the Query Result from the Method, PopulateVideosWithAthleteID

1 个答案:

答案 0 :(得分:0)

您需要更改方法PopulateVideosWithAthleteID,如下所示。

private List<AthleteVideoViewModel> PopulateVideosWithAthleteID(int anAthleteId)
{
    using (SqlConnection connection = new SqlConnection(DatabaseConnection.GetConnectionString("acgvideodbConnectionString")))
    {
        using (SqlCommand cmd = connection.CreateCommand())
        {
            try
            {
                List<AthleteVideoViewModel> vidmod = new List<AthleteVideoViewModel>();
                cmd.CommandText = "SELECT Athlete_Name.AthleteID AS AthleteID, Athlete_Video.anAthleteID AS anAthleteID, Athlete_Video.AthleteVideo AS AthleteVideo FROM Athlete_Video INNER JOIN Athlete_Name ON Athlete_Name.AthleteID = Athlete_Video.anAthleteID WHERE Athlete_Video.anAthleteID = @anAthleteId";
                cmd.Parameters.Add(new SqlParameter("@anAthleteId", anAthleteId);
                SqlDataAdapter sda = new SqlDataAdapter(cmd);
                DataSet ds = new DataSet();
                sda.Fill(ds);
                DataTable dt = new DataTable();
                ds.Tables.Add(dt);
                vidmod = ds.Tables[0].AsEnumerable().Select(dataRow => new AthleteVideoViewModel { AthleteID = dataRow.Field<int>("AthleteID"), anAthleteID = dataRow.Field<int>("anAthleteID"), AthleteVideo = dataRow.Field<string>("AthleteVideo") }).ToList();

                return vidmod;
            }
            finally
            {
            }
        }
    }
}

现在,此方法将返回所提供的AthleId的视频列表。

从控制器操作中调用此方法,以填充模型类的属性。

public PartialViewResult GetAthleteVideo(int AthleteID)
{
    var vidModels = new AthleteVideoViewModel();
    vidModels.AthleteDbList = PopulateVideosWithAthleteID(AthleteID);
    return PartialView("_ShowAthlete", vidModels);
}

PartialView代码更改如下。

@model ACGteam.ViewModels.AthleteVideoViewModel
@{
    ViewBag.Title = "_ShowAthlete";
}
<div class="row">
    <div style="display: block; text-align: center;">
        <div>
            <img height="75" width="100" src="/Img/AvantCoeurLogoGirls.png" />
        </div>
        <div class="col-md-12 display-label">
            @Html.DisplayFor(items => items.AthleteName)
        </div>

        <div class="box">
            <div class="row">
                @{
                    for (var count = 0; count < Model.AthleteDbList.Count; count++)
                    {
                        <div class="col-md-6 col-lg-4 img-responsive">
                            <video style="height:250px; width:250px" controls="controls">
                                <source src="@Html.DisplayFor(vidmod => vidmod.AthleteDbList[count].AthleteVideo)" type="video/mp4" />
                            </video>
                            <br />
                            <strong>GroupShow_Candyland</strong>
                        </div>
                    }
                }
            </div>
        </div>
    </div>
 </div>

这可以解决您的问题。