如何使用动态id调用ajax函数- MVC

how to call an ajax function with dynamic ID's- MVC

本文关键字:函数 MVC ajax 调用 何使用 动态 id      更新时间:2023-09-26

我尝试从另一个下拉列表中的选定项更新下拉列表。该页面包含多个具有相同数据的下拉列表的选项

@model List<CimenaCityProject.Models.TimeScreening>
@{
ViewBag.Title = "Create";
int? numberOfNewTimeScreening = ViewBag.number;
if (!numberOfNewTimeScreening.HasValue)
{
    numberOfNewTimeScreening = 1;
}
for (int i = 0; i < numberOfNewTimeScreening; i++)
{
}
var SelectMovieID = (SelectList)ViewBag.MovieID;
var SelectHomeCinemaID = (SelectList)ViewBag.HomeCinemaID;
}
<h2>Create</h2>

@using (Html.BeginForm("Create", "TimeScreening", FormMethod.Post))
{
     @Html.AntiForgeryToken()
<div class="form-horizontal">
    <h4>TimeScreening</h4>
    <hr />
    @Html.ValidationSummary(true)
    <table>
        <tr>
            <th>
                @Html.Label("ShowTime", new { @class = "control-label col-md-2" })
            </th>
            <th>
                @Html.Label("Theatres", new { @class = "control-label col-md-2" })
            </th>
            <th>
                @Html.Label("Date", new { @class = "control-label col-md-2" })
            </th>
            <th>
                @Html.Label("Price", new { @class = "control-label col-md-2" })
            </th>
            <th>
                @Html.Label("Is Displayed", new { @class = "control-label col-md-2" })
            </th>
            <th>
                <div class="col-md-offset-2 col-md-10">
                    <input type="submit" value="Create" class="btn btn-default" />
                </div>
            </th>
        </tr>
        @for (int i = 0; i < numberOfNewTimeScreening.Value; i++)
        {
            string HomeCinemaID = "["+i + "].MovieTheaters.HomeCinemaID".ToString();
            string TheatresID = "["+ i + "].TheatresID".ToString();   
            <tr>
                <td>
                    <div class="col-sm-8">
                        <br />
                        @Html.DropDownListFor(model => model[i].MovieShowTime.Single().MovieID, SelectMovieID, "Select Movie")
                        <br /><br />
                        @Html.DropDownListFor(model => model[i].MovieShowTimeID, Enumerable.Empty<SelectListItem>(), "--Loading Value--")
                        @Html.ValidationMessageFor(model => model[i].MovieShowTimeID)
                    </div>
                </td>
                <td>
                    <div class="col-sm-8">
                        <br />
                        @Html.DropDownListFor(model => model[i].MovieTheaters.HomeCinemaID, SelectHomeCinemaID, "Select Home Cinema",
                 new { id = HomeCinemaID.ToString(), name = HomeCinemaID.ToString() })
                        <br /><br />
                        @Html.DropDownListFor(model => model[i].TheatresID, Enumerable.Empty<SelectListItem>(), "--Loading Value--",
                        new {id=TheatresID.ToString(), name = TheatresID.ToString()})
                        @Html.ValidationMessageFor(model => model[i].TheatresID)
                    </div>
                </td>
                <td>
                    <div class="col-sm-8">
                        <br />
                        @Html.EditorFor(model => model[i].Date)
                        @Html.ValidationMessageFor(model => model[i].Date)
                    </div>
                </td>
                <td>
                    <div class="col-sm-8">
                        <br />
                        @Html.EditorFor(model => model[i].Price)
                        @Html.ValidationMessageFor(model => model[i].Price)
                    </div>
                </td>
                <td>
                    <div class="col-sm-8">
                        <br />
                        @Html.EditorFor(model => model[i].IsDisplayed)
                        @Html.ValidationMessageFor(model => model[i].IsDisplayed)
                    </div>
                </td>
                <td></td>
            </tr>
        }
    </table>
</div>
}

,如您所见,获取页面编号和for循环复制数据。当for循环开始时,他为下拉列表提供了动态id

model[i].TheatresID 

当用户选择家庭影院时,ajax必须启动并加载连接到家庭影院的影院。

这里的代码包含了HomeCinema和Movie的函数。最后一段代码转换为JSON DATETIME。

Ajax CODE:
<script type="text/javascript">
  //function for HomeCinema. 
    $(function () {
        $('@HomeCinemaID.ToString()').change(function () {
            alert("ok1")
            $.ajax({
                type: "POST",
                url: '@Url.Action("GetTheatres","TimeScreening")',
                data: { CinemaID: $('@HomeCinemaID.ToString()').val() },
                success: function (data) {
                    $(@TheatresID.ToString()).html('');
                    $.each(data, function (id, option) {
                        $(@TheatresID.ToString()).append($('<option></option>').val(option.id).html(option.name));
                    });
                },
                error: function (xhr, ajaxOptions, thrownEror) {
                    alert("Error by loading the Theatres");
                }
            });
        });
   });

    $(function () {
        $('#'+j + '.MovieID').change(function () {
            $.ajax({
                type: "POST",
                url: '@Url.Action("GetShowTime", "TimeScreening")',
                data: { MovieID: $('#' + j + '.MovieID').val() },
                dataType: 'json',
                success: function (data) {
                    $('#' + j + '.MovieShowTimeID').html('');
                    $.each(data, function (id, option) {
                        var name = DatetimeConverter(option.name)
                        $('#' + j + '.MovieShowTimeID').append($('<option></option>').val(option.id).html(name));
                    });
                },
                error: function (xhr, ajaxOptions, thrownEror) {
                    alert("False" + xhr + "..." + ajaxOptions + "... " + thrownEror);
                }
            });
        });
    });

// START Datetime Converters
function DateConverter(date) {
    var aux = null;
    if (date != null) {
        aux = date.substring(6);
        aux = aux.substring(0, aux.indexOf(')'));
    }
    return aux != null ? getISODate(new Date(parseInt(aux))) : "";
}
function DatetimeConverter(date) {
    var aux = null;
    if (date != null) {
        aux = date.substring(6);
        aux = aux.substring(0, aux.indexOf(')'));
    }
    return aux != null ? getISODateTime(new Date(parseInt(aux))) : "";
}
function getISODate(d) {
    // padding function
    var s = function (a, b) { return (1e15 + a + "").slice(-b) };
    // default date parameter
    if (typeof d === 'undefined') {
        d = new Date();
    };
    // return ISO datetime
    return zeroPad(d.getDate(), 2) + '/' +
    zeroPad(s(d.getMonth() + 1, 2), 2) + '/' +
    zeroPad(d.getFullYear(), 4);
}
function getISODateTime(d) {
    // padding function
    var s = function (a, b) { return (1e15 + a + "").slice(-b) };
    // default date parameter
    if (typeof d === 'undefined') {
        d = new Date();
    };
    // return ISO datetime
    return zeroPad(d.getHours(), 2) + ":" +
    zeroPad(d.getMinutes(), 2) + ":" +
    zeroPad(d.getSeconds(), 2);
}
function zeroPad(num, places) {
    var zero = places - num.toString().length + 1;
    return Array(+(zero > 0 && zero)).join("0") + num;
}
// END Datetime Converters

</script>
    }
    }
代码:

        public ActionResult GetTheatres(int? CinemaID)
    {
        var data = (from d in db.Theaters
                    where d.HomeCinemaID == CinemaID
                    select new
                    {
                        id = d.MovieTheatersID,
                        name = d.TheatersName
                    }).ToList();
        return Json(data,JsonRequestBehavior.AllowGet);
    }
    public JsonResult GetShowTime(int? MovieID)
    {
        var data = (from m in db.MovieShowTimes
                    where m.MovieID == MovieID
                    select new
                    {
                        id = m.MovieShowTimeID,
                        name = m.ShowTime
                    }).ToList();
        return Json(data, JsonRequestBehavior.AllowGet);
    }

之后,控制器获取用户制作的列表并添加到数据库。

控制器:

    // POST: /TimeScreening/Create
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "TimeScreeningID,MovieShowTimeID,TheatresID,Date,Price,IsDisplayed")] List<TimeScreening> Timescreening)
    {
        int check = 0;
        foreach (var timescreening in Timescreening)
        {
            if (ModelState.IsValid)
            {
                db.TimeScreening.Add(timescreening);
                check = db.SaveChanges();
            }
        }
        if (check== 1)
        {
            return RedirectToAction("Index");
        }
        return View("Create", Timescreening);

    }

当我使用一个元素(没有for循环和静态id)时,这个工作很完美我如何能使它与多个和动态id的工作?

Ziv,而不是将更改事件处理程序附加到ID选择器,而是使用类来完成。对于每个你希望按照你编码的方式处理事件的下拉菜单,添加这个特定的类。

不要在你的下拉菜单中定义ID元素。

的例子:

<select class='myDropDown' ...>
</select>
<select class='myDropDown' ...>
</select>
**jquery**:
$(".myDropDown").change(function(){
    // your code here
});