ASP.NET MVC按DropDownList中的选定项目对列表进行排序 [英] ASP.NET MVC Sort Listing by Selected item in DropDownList

查看:37
本文介绍了ASP.NET MVC按DropDownList中的选定项目对列表进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的数据库中有一个清单列表.在我的视图上,我有一个包含类别的DropDownList.一个类别包含许多列表.

当我选择一个特定类别时,我只希望显示那些选择了该类别的列表.

我主要担心的是如何生成JQuery以便在我的ListingController中调用我的SortListing方法.

这是当前的HTML(Razor):

  @ Html.DropDownListFor(m => m.Categories,Model.Categories,选择类别") 

我的SortListing方法:

 公共列表< Listing>SortListing(字符串categoryId){var listings = new List< Listing>();foreach(_service.ListAllEntities< Listing>()中的var列表){如果(listing.CategoryId == categoryId){listings.Add(清单);}}返回清单;} 

编辑,我有以下内容.将categoryGuid放入null.

这是我的代码:

  $(function(){$('#SelectedCategoryGuid').change(function(){var url = $(this).data('url');var categoryId = $(this).val();$ .ajax({网址:url,类型:"GET",快取:false,数据:{categoryId:categoryId},成功:功能(结果){//TODO:操纵从控制器动作返回的结果}});});});</script>< h2>索引</h2>@ Html.ActionLink(创建新列表",创建")< br/>< strong>过滤器列表</strong>@ Html.DropDownListFor(m =>m.SelectedCategoryGuid,型号,类别,选择一个类别",新的 {id ="SelectedCategoryGuid",data_url = Url.Action("SortListing","Listing")}) 

解决方案

我主要担心的是如何生成JQuery来调用我的SortListing我的ListingController中的方法.

实际上,您还应该担心其他问题,我将在我的回答中全力以赴.

您的 DropDownListFor 帮助器存在问题.您在模型上使用了相同的属性来绑定选定的类别值和错误的类别列表.DropDownListFor帮助器的第一个参数表示一个lambda表达式,该表达式指向您的视图模型上的原始类型属性:

  @ Html.DropDownListFor(m =>m.CategoryId,型号,类别,选择一个类别",新的 {id ="categoryDdl",data_url = Url.Action("SortListing","Listing")}) 

,然后订阅 .change()事件并触发AJAX请求:

  $(function(){$('#categoryDdl').change(function(){var url = $(this).data('url');var categoryId = $(this).val();$ .ajax({网址:url,类型:"GET",快取:false,数据:{categoryId:categoryId},成功:功能(结果){//TODO:操纵从控制器动作返回的结果}});});}); 

现在让我们看一下您的 SortListing 控制器操作,因为它存在问题.在ASP.NET MVC中,标准约定指示控制器操作必须返回ActionResults.在您的情况下,您似乎正在返回一些 List< Listing> .因此,您首先要决定的是您要使用的格式.一种可能性是将这些列表作为JSON格式的值返回:

  public ActionResult SortListing(字符串categoryId){var列表= _service.ListAllEntities< Listing>()哪里(x => x.CategoryId == categoryId).ToList();返回Json(listings,JsonRequestBehavior.AllowGet);} 

在这种情况下,您将在AJAX成功回调中收到此列表集合,并且必须更新DOM:

 成功:函数(结果){//结果代表一个清单数组//这样您就可以遍历它们并生成一些DOM元素} 

另一种可能性是让您的控制器操作返回部分视图:

  public ActionResult SortListing(字符串categoryId){var列表= _service.ListAllEntities< Listing>()哪里(x => x.CategoryId == categoryId).ToList();返回PartialView(清单",清单);} 

,然后您将有一个相应的局部视图:

  @model List< Listing>@foreach(模型中的var列表){< div> @ listing.SomeProperty</div>} 

,然后在成功回调中,您将刷新一些包含占位符的内容:

 成功:函数(结果){$('#SomeDivIdThatWrapsAroundTheListingsPartial').html(结果);} 

因此,回顾一下,您可以让控制器动作返回JSON,然后使用javascript手动构建相应的DOM树,或者返回一个已经包含相应标记的局部视图,并使用此局部刷新一些包含div的

I have a List of Listings within my Database. On my View, I have a DropDownList which contains categories. A category contains many listings.

When I select a specific category, I wish to only display those listings which have the category selected.

My main worry is how to generate the JQuery to call my SortListing method in my ListingController.

Here is the current HTML (Razor):

@Html.DropDownListFor(m => m.Categories, Model.Categories, "Select a Category")

My SortListing Method:

public List<Listing> SortListing(string categoryId)
{
    var listings = new List<Listing>();

    foreach (var listing in _service.ListAllEntities<Listing>())
    {
        if (listing.CategoryId == categoryId)
        {
            listings.Add(listing);
        }
    }

    return listings;
}

EDIT I have the following. Put the categoryGuid is coming in null.

This is my code:

    $(function () {
        $('#SelectedCategoryGuid').change(function () {
            var url = $(this).data('url');
            var categoryId = $(this).val();
            $.ajax({
                url: url,
                type: 'GET',
                cache: false,
                data: { categoryId: categoryId },
                success: function (result) {
                    // TODO: manipulate the result returned from the controller action
                }
            });
        });
    });

</script>

<h2>Index</h2>
@Html.ActionLink("Create New Listing", "Create")
<br/>
<strong>Filter Listings</strong>
@Html.DropDownListFor(
    m => m.SelectedCategoryGuid, 
    Model.Categories, 
    "Select a Category", 
    new {
        id = "SelectedCategoryGuid",
        data_url = Url.Action("SortListing", "Listing") 
    }
)

解决方案

My main worry is how to generate the JQuery to call my SortListing method in my ListingController.

Actually you should be having other worries as well that I will try to cover throughout my answer.

There's an issue with your DropDownListFor helper. You have used the same property on your model for both binding the selected category value and the list of categories which is wrong. The first parameter of the DropDownListFor helper represents a lambda expression pointing to a primitive type property on your view model:

@Html.DropDownListFor(
    m => m.CategoryId, 
    Model.Categories, 
    "Select a Category", 
    new { 
        id = "categoryDdl",
        data_url = Url.Action("SortListing", "Listing") 
    }
)

and then subscribe to the .change() event and trigger the AJAX request:

$(function() {
    $('#categoryDdl').change(function() {
        var url = $(this).data('url');
        var categoryId = $(this).val();
        $.ajax({
            url: url,
            type: 'GET', 
            cache: false,
            data: { categoryId: categoryId },
            success: function(result) {
                // TODO: manipulate the result returned from the controller action
            }
        });
    });
});

Now let's take a look at your SortListing controller action because there are issues with it. In ASP.NET MVC standard convention dictates that controller actions must return ActionResults. In your case you seem to be returning some List<Listing>. So the first thing you have to decide is the format you would like to use. One possibility is to return those listings as JSON formatted values:

public ActionResult SortListing(string categoryId)
{
    var listings = _service
        .ListAllEntities<Listing>()
        .Where(x => x.CategoryId == categoryId)
        .ToList();

    return Json(listings, JsonRequestBehavior.AllowGet);
}

In this case inside your AJAX success callback you will receive this collection of listings and you will have to update your DOM:

success: function(result) {
    // result represents an array of listings
    // so you could loop through them and generate some DOM elements
}

Another possibility is to have your controller action return a partial view:

public ActionResult SortListing(string categoryId)
{
    var listings = _service
        .ListAllEntities<Listing>()
        .Where(x => x.CategoryId == categoryId)
        .ToList();

    return PartialView("Listings", listings);
}

and then you will have a corresponding partial view:

@model List<Listing>
@foreach (var listing in Model)
{
    <div>@listing.SomeProperty</div>
}

and then inside the success callback you will refresh some containing placeholder:

success: function(result) {
    $('#SomeDivIdThatWrapsAroundTheListingsPartial').html(result);
}

So to recap you could either have the controller action return JSON and then manually build the corresponding DOM tree using javascript or return a partial view which will already contain the corresponding markup and simply refresh some containing div with this partial.

这篇关于ASP.NET MVC按DropDownList中的选定项目对列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆