Asp.net MVC的行动和观点的问题 [英] Asp.net MVC action and view issue

查看:114
本文介绍了Asp.net MVC的行动和观点的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我被困在一个奇怪的局面。我有一个传递的类别字符串控制器动作。然后操作方法在数据库中的字符串相匹配并收集子类别和产品为它。现在,我想是实现分页的产品,如果他们是大于10的看法是一个强类型的一个类别型号

I am stuck in a weird situation. I have a controller action which is passed a category string. Then the action method matches the string in the database and collects the sub categories and products for it. Now, What I want is to achieve pagination for the products if they are greater than 10. The view is a strongly-typed one for Category Model

以下是code的操作方法。

Following is the code for action method.

    public ActionResult Catalog(string id)
    {
        Category catalog = pe.Categories.Where(cat => cat.CategoryName == id).Single();
        return View(catalog);
    }

我在我的其他项目进行分页类似以下,但在这种情况下收集是一个IQueryable不能在自其只为一类上述情况。另外,我已经传递参数在上面的功能,我这样怎么能传递两个。

I have done pagination in my other project like following but in that case the collection was an IQueryable which can't be in the above case since its just for one category. Also, I am already passing an argument in the above function so how can i pass two.

    public ViewResult Index(int? page)
    {
        IQueryable<Album> albums = db.Albums.Include(a => a.Genre).Include(a => a.Artist).OrderBy(a => a.Title);
        int pageIndex = page ?? 1;
        return View(albums.ToPagedList(pageIndex, PageSize));
    }

请告诉我,你将如何应对这样的场景。

Please tell me how will you tackle such scenario.

推荐答案

使用一个视图模型来收集只是你想在视图中显示的信息。在你的选择逻辑,选择进入顶级从类别和协会的相关部分属性视图模型。你当然可以有多个参数的方法。提供额外的参数给路由值在ActionLink的形式或辅助方法,它应该构造URL正确引用你的行动。注意:您将需要改变模型的类型,在视图以及以匹配从操作。

Use a viewmodel to collect just the information that you want to show in your view. In your selection logic, select into the viewmodel the top-level attributes from the category and the relevant parts of the association. You can certainly have more than one parameter to the method. Supply the extra parameters to the route values in your ActionLink or Form helper methods and it should construct the Url properly to reference your action. Note you will need to change the type of the model in the view as well to match that from the action.

public ActionResult Catalog(string id, int? page)
{
    page = page ?? 1;
    var category = pe.Categories.SingleOrDefault(cat => cat.CategoryName == id);
    var model = new CatalogViewModel
                {
                       ID = category.ID,
                       Name = category.CategoryName,
                       Subcategories = category.Subcategories,
                       Products = category.Products.ToPagedList( page, PageSize )
                };

    return View(model);
}

查看(样品)

@if (Model.Products.Page < Model.Products.Pages)
{
    @Html.ActionLink( "Next",
                      "catalog",
                      new { id = Model.ID, page = Model.Products.Page + 1 } ) 
}

这篇关于Asp.net MVC的行动和观点的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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