jQuery MVC 4 Razor 使用 Ajax 表单更新 foreach 循环

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19626480/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 00:19:10  来源:igfitidea点击:

MVC 4 Razor using Ajax forms to update a foreach loop

ajaxasp.net-mvcjqueryasp.net-mvc-4razor

提问by Keltanis

Where to start...I can find similar things on the Internet as to how, but they never seem to work with my specific way of wanting to do something. I have tried with and without partial views with very little success.

从哪里开始......我可以在互联网上找到类似的东西,但它们似乎从来没有按照我想要做某事的特定方式工作。我曾尝试使用和不使用部分视图,但收效甚微。

Quick rundown: I have a strongly-typed View with an Ajax form. underneath the form, I have a foreach loop that repeats a code block. I need to be able to update the code block from the forms choices (filters).

快速概述:我有一个带有 Ajax 表单的强类型视图。在表单下方,我有一个重复代码块的 foreach 循环。我需要能够从表单选项(过滤器)更新代码块。

Here's my View, 'FindATeacher.cshtml', as it currently stands (after trying many different ideas):

这是我的视图,“FindAteacher.cshtml”,目前的情况(在尝试了许多不同的想法之后):

@model Teachers.Models.OmniModel
@{
    ViewBag.Title = "FindATeacher";
    Layout = "~/Views/Shared/_Layout.cshtml";

}
<h2>Find a Teacher</h2>
@using (Ajax.BeginForm("FilterTeachers", "Home", new AjaxOptions { HttpMethod = "Post", OnSuccess = "onSuccess" }))
{
    <div id="ContentFilter">
        <div class="filterLabels">
            <p>Search by Name</p>
            <p>Filter By Instrument</p>
            <p>Filter By City</p>
        </div>
        <div class="filterObjects">
            <p>
                <input type="text" id="nameTXT" />
                <button type="submit" id="findButton">find</button>
            </p>
            <p>@Html.DropDownList("InstrumentID", (SelectList)Model.Instruments, "-- Select an Instrument --", new { id = "instrumentDD" })</p>
            <p>@Html.DropDownList("CityID", (SelectList)Model.Cities, "-- Select a City --", new { id = "cityDD" })</p>
        </div>
    </div>
}
<hr />
@foreach (var r in Model.Teachers)
{
    <div id="ContentResults">
        <div id="avatar">
            <img src="i" />
        </div>

        <div id="demographics">
            <h6>@r.Teacher</h6>
            <strong>@r.StudioName</strong>
            <p><a href="#">@r.URL</a></p>
            <p>@r.StreetAddress</p>
            <p>@r.City, @r.AddressStateID @r.Zip</p>
            <p>@r.Phone</p>
            <p>@r.EmailAddress</p>
        </div>
        <div id="studioDetails">
            <p><strong>Instrument(s) Taught</strong></p>
            <p>
                @{
    var instrumentString = r.Instruments.Aggregate("", (a, b) => a + b.Instrument + ", ");
    if (instrumentString.Length != 0)
    {
        instrumentString = instrumentString.Remove(instrumentString.LastIndexOf(","));
    }
                }
                @instrumentString
            </p>
            <br />

            @if (r.Information != "" && r.Information != null)
            {
                <p><strong>Information</strong></p>
                <p>@r.Information</p>
            }
        </div>
    </div>
}

Now here's my Controller. I get the results back correctly in the Controller, just not updating the code block:

现在这是我的控制器。我在控制器中正确返回结果,只是不更新​​代码块:

public ActionResult FindATeacher()
        {
            Model.Instruments = new SelectList(TeacherService.GetInstrumentList(0),"InstrumentID","Instrument");
            Model.Cities = new SelectList(TeacherService.GetCityList(),"CityID","City");
            Model.Teachers = TeacherService.GetTeacherList("", 0);
            return View(Model);
        }

        [HttpPost]
        public JsonResult FilterTeachers(String teacherName, String instrumentID, String cityID)
        {
            Model.Teachers = TeacherService.GetTeacherList("John", 0, 0);
            return Json(Model.Teachers);
        }

Thanks.

谢谢。

回答by StriplingWarrior

@VishalVaishya presents the right idea, but there's a simpler way, which doesn't involve custom javascript code: AjaxOptions has an UpdateTargetId property that the AJAX toolkit will interpret to mean you want the given target to be updated with the results sent back from the controller.

@VishalVaishya 提出了正确的想法,但有一种更简单的方法,它不涉及自定义 javascript 代码:AjaxOptions 有一个 UpdateTargetId 属性,AJAX 工具包将其解释为意味着您希望使用从控制器。

FindATeacher.cshtml:

FindAteacher.cshtml:

@using (Ajax.BeginForm("FilterTeachers", "Home", new AjaxOptions { 
    HttpMethod = "Post", UpdateTargetId = "TeacherList" }))
{
    ...
}
<hr />
<div id="TeacherList">
    @Partial("TeacherList", Model.Teachers)
</div>

TeacherList.cshtml

教师列表.cshtml

@model IEnumerable<Teacher>
@foreach(var teacher in Model)
{
   ...
}

Controller action:

控制器动作:

    [HttpPost]
    public ActionResult FilterTeachers(String teacherName, String instrumentID, String cityID)
    {
        Model.Teachers = TeacherService.GetTeacherList(teacherName, instrumentID, cityID);
        return PartialView("TeacherList", Model.Teachers);
    }

回答by Vishal Vaishya

You can try following method:

您可以尝试以下方法:

Separate your foreach loop into another partial view. And load your partial view on filter / click event and pass filtered parameters to your controller-action.

将您的 foreach 循环分成另一个部分视图。并在过滤器/单击事件上加载您的部分视图,并将过滤后的参数传递给您的控制器操作。

JS change event code will be something like this:

JS 更改事件代码将是这样的:

var teacherName = ''; //get your selected teachername
var instrumentID = ''; //get your selected instrumentid
var cityID = ''; //get your selected city id

var url = '@Url.Action("FilterTeachers", "ControllerName", new { teacherName = "teacher-Name", instrumentID="instrument-ID", cityID="city-ID" })';

url = url.replace("teacher-Name", teacherName).replace("instrument-ID", instrumentID).replace("city-ID", cityID);

$('#result').load(url);