944 messaggi dal 11 febbraio 2013
ciao
vorrei realizzare in MVC una pagina dove visualizzare un catalogo fotografico di prodotto come in oggetto e vorrei anche applicare dei filtri ...

avete un esempio di base da poter studiare e ampliare?

grazie in ogni caso

ciao
944 messaggi dal 11 febbraio 2013
Ho provato a scrivere questo codice

public ActionResult GetData(int? pageIndex, int? pageSize, string color)
        {
            System.Threading.Thread.Sleep(2000);

            var product = _context.Product.Where(i => i.ProductLine != null).AsQueryable();

            if (!string.IsNullOrEmpty(color))
                product = product.Where(i => i.Color == color);

             product = product.OrderBy(i=>i.ProductID)
                              .Skip((int)(pageIndex * pageSize))
                              .Take((int)pageSize);

            return Json(product, JsonRequestBehavior.AllowGet);
        }


e nella pagina
@Html.DropDownList("Colors", new SelectList(ViewBag.Colors), "Colori", new { @class="form-control"})

 <button class="btn btn-default js-search">Search</button>


 <div id="container" class="row">
     
 </div>
<div id="progress" style="display:none">
    <h4>Loading...</h4>
</div>

@section scripts{

    <script>

        var pageSize = 10;
        var pageIndex = 0;
        var colorSelected;

        $(document).ready(function () {

            $('.js-search').click(function () {
                colorSelected = $('#Colors option:selected').text();
                $("#container").empty();
                pageIndex = 0; GetData();
            });

            GetData();

            $(window).scroll(function () {
                if ($(window).scrollTop() ==
                    $(document).height() - $(window).height()) {
                    GetData();
                }
            });
        });

        function GetData() {
            $.ajax({
                type: 'GET',
                url: '/Home/GetData',
                data: { "pageindex": pageIndex, "pagesize": pageSize, "color":colorSelected },
                dataType: 'json',
                success: function (data) {
                    if (data != null) {
                        for (var i = 0; i < data.length; i++) {
                            $("#container").append("<div class='col-md-6'>" +
                                "<div class='col-md-4'><img src='/Image/Show/162' height='100' width='100' alt='Product Image' /></div>" +
                                 "<div class='col-md-2'>" + data[i].ProductID + "</div>" +
                                 "<div class='col-md-3'>" + data[i].Name +  "</div>" +
                                 "<div class='col-md-3'>" + data[i].Color + "</div>" +
                                "</div>");
                        }
                        pageIndex++;
                    } 
                },
                beforeSend: function () {
                    $("#progress").show();
                },
                complete: function () {
                    $("#progress").hide();
                },
                error: function () {
                    alert("Error while retrieving data!");
                }
            }).done(function (response) {
                if (response.length === 0) {
                    $("#progress").hide();
                    $("#container").append("<h2>" + 'end' + "</h2>");
                }
            });
        }

    </script>

}


è la strada sbagliata? Volendo implementare un search piu ampio per filtrare il model è corretto procedere cosi?
Non l'ho mai fatto

grazie
944 messaggi dal 11 febbraio 2013
Ho trovato anche un esempio con le partial view e mi pare che vada bene
solo la domanda rimane: se voglio espandere di molto i parametri di ricerca vado bene per 'la stazione' oppure
vado contro un muro:) ?

mvc
AdventureWorksEntities _data = new AdventureWorksEntities();
        const int recordsPerPage = 9;

        // GET: Product
        public ActionResult Index(int? id, string color)
        {
            GetViewBag();

            var page = id ?? 0; // ???

            var model = _data.Product.AsNoTracking().AsQueryable();

            model = FilterModel(model, color);
            model = GetPaginatedProducts(model, page).AsQueryable();

            if (Request.IsAjaxRequest())
                return PartialView("_partialProducts", model);

            
            return View("Index", model.Take(recordsPerPage));
        }

        
        private IEnumerable<Product> GetPaginatedProducts(IQueryable<Product> model,  int page = 1)
        {
            System.Threading.Thread.Sleep(2000);

            var skipRecords = page * recordsPerPage;
        
            return model.OrderBy(i => i.ProductID)
                        .Skip(skipRecords)
                        .Take(recordsPerPage);
        }

        private IQueryable<Product> FilterModel(IQueryable<Product> model, string color)
        {
            model = model.Where(x => x.ProductLine != null);

            if (!string.IsNullOrEmpty(color))
                model= model.Where(i => i.Color == color);

            return model;
        }

        public void GetViewBag()
        {
            ViewBag.Colors = _data.Product.Where(i => i.ProductLine != null).
                                           Select(i => i.Color).
                                           Distinct();

            ViewBag.Category = _data.Product.Where(i => i.ProductLine != null).
                                             Select(i => i.ProductSubcategory.Name)
                                            .Distinct();
                                            
        }
    }


js
<div>
    @Html.DropDownList("Colors", new SelectList(ViewBag.Colors), "Colori")
    @Html.DropDownList("Category", new SelectList(ViewBag.Category), "Categoria")

    <button class="js-search">Filtra</button>
</div>

<br />

<div id="productList">
    @Html.Partial("_partialProducts")
</div>

<div id="loading" style="display:none;">
    <p><img src="/Content/Images/loading.gif"></p>
</div>

@section scripts{
    <script>
        var $window = $(window);
        var page = 0;
        var _inCallback = false;
        var color =  "";

        function windowScroll() {
            if ($window.scrollTop() ==
                $(document).height() - $window.height()) {
                $window.off('scroll');
                loadProducts();
            }
        }

        $(document).ready(function () {

            $('.js-search').click(function () {
                color = $('#Colors option:selected').text();
                $("#productList").empty();
                page = 0;
                $(window).bind('scroll');
                loadProducts();
                _inCallback = false;
              
            });

            loadProducts();

            $window.scroll(windowScroll);
        });

        function loadProducts() {
        
            if (page > -1 && !_inCallback ) {
                _inCallback = true;
                page++;

                $('div#loading').show();
                
                $.ajax({
                    type: 'GET',
                    url: '/Product/Index/',
                    data: { "id": page, "color": color },
                    dataType: 'html',
                    success: function (data) {
                        if (data.includes('dataEnd')) {
                           
                        } else {

                            if (data != null) {
                                $window.on('scroll', windowScroll);
                                $("#productList").append(data);
 
                            } else {
                                page = -1;//non raggiunge                               
                            }
                        }
                        _inCallback = false;
                        $('div#loading').hide();
                    },
                    beforeSend: function () {
                        $("div#loading").show();
                    },
                    complete: function () {
                        $("div#loading").hide();
                    },
                    error: function () {
                        alert("Error while retrieving data!");
                    }
                });
            }
        }

        
    </script>
}


partialView
@model IEnumerable<MVC_InfinityScroll.Models.Product>

@if (Model.Any())
{
    <div class="row">

        @foreach (var item in Model)
        {
            <div class="col-md-4" >
                <div class="row">
                    <img src="@Url.Action("Show", "Image", new { id = item.ProductProductPhoto.FirstOrDefault().ProductPhotoID })"
                         class="img-responsive img-thumbnail" alt="Product Image" />
                </div>
                <div class="row">               
                   <b>Number</b> @item.ProductNumber <br/>
                   <b>Name</b>   @item.Name <br />
                   <b>Color</b>  @item.Color <br />
                   <b>Price</b> $@item.ListPrice.ToString("##.00") <br />
                </div>
            </div>
        }

    </div>

} else{
    <text>dataEnd</text>
}

Torna al forum | Feed RSS

ASPItalia.com non è responsabile per il contenuto dei messaggi presenti su questo servizio, non avendo nessun controllo sui messaggi postati nei propri forum, che rappresentano l'espressione del pensiero degli autori.