【问题标题】:How to pass Id with RenderAction from View that inherits PagedList<ViewModel >MVC 4如何从继承 PagedList<ViewModel>MVC 4 的 View 中使用 RenderAction 传递 Id
【发布时间】:2014-12-09 08:39:16
【问题描述】:

我有在弹出模式中呈现创建视图的渲染操作。但是模型不允许传递类别的id,并调用错误:

The parameters dictionary contains a null entry for parameter 'categoryId' of non-nullable type 
'System.Int32' for method 'System.Web.Mvc.ActionResult Create(Int32)' in 
'PasswordCloudApp.Controllers.EntryController'. An optional parameter must be a reference type,
 a nullable type, or be declared as an optional parameter.

索引视图:

@model PagedList.IPagedList<PasswordCloudApp.ViewModels.EntryViewModel>

@{Html.RenderAction("Create", "Entry", new { categoryId = Model.CategoryId -->
  but don't allow to access .CategoryId });}

@Html.Partial("_Entries", Model)

动作方法索引:

 public ActionResult Index(int categoryId, int page = 1)
    {
        var category = _db.Categories.Find(categoryId);

        var model =
             db.Query<Entry>()
                .OrderBy(en=>en.Id)
                .Where(en=>en.CategoryId == categoryId)
                .Select(en => new EntryViewModel
                {
                    Id = en.Id,
                    Title = en.Title,
                    Username = en.Username,
                    Password = en.Password,
                    Url = en.Url,
                    Description = en.Description,
                }).ToPagedList(page, 10);

   return View(model);
 }

关于如何将 CategoryId 传递给 RenderAction 有什么建议吗?

【问题讨论】:

    标签: asp.net asp.net-mvc entity-framework asp.net-mvc-4


    【解决方案1】:

    您似乎没有在模型中填充 CategoryId。

    试试:

    public ActionResult Index(int categoryId, int page = 1)
    {
       var category = _db.Categories.Find(categoryId);
    
       var model =
             db.Query<Entry>()
               .OrderBy(en => en.Id)
               .Where(en => en.CategoryId == categoryId)
               .Select(en => new EntryViewModel
                {
                   Id = en.Id,
                   CategoryId = en.CategoryId,
                   Title = en.Title,
                   Username = en.Username,
                   Password = en.Password,
                   Url = en.Url,
                   Description = en.Description,
                 }).ToPagedList(page, 10);
    
                return View(model);
    }
    

    【讨论】:

    • 谢谢@JayL 的回答,你对填充 CategoryId 是正确的。
    【解决方案2】:

    如果 PagedList.IPagedList 是一个集合类型,你肯定不能访问 categoryId 属性。

    【讨论】:

    • 是的,你是对的 PagedList.IPagedList 是一个集合类型,绝对不能访问 categoryId 属性。但是知道如何解决这个问题并传递 categoryId 吗?
    • 页面是只有一个action link还是基于categoryId的几个?
    • 一个。我也尝试过使用 ActionLink,但无法访问。
    • 如果集合中所有值的 categoryId 相同,则使用类似 Model.FirstorDefault().CategoryId
    • 非常感谢@Venkatesh N,就像你说的那样,我被这个问题困扰了两天。
    猜你喜欢
    • 1970-01-01
    • 2012-05-13
    • 2023-03-27
    • 1970-01-01
    • 1970-01-01
    • 2013-09-21
    • 1970-01-01
    • 1970-01-01
    • 2014-09-27
    相关资源
    最近更新 更多