使用PagedList.MVC时无法使用强类型视图

时间:2016-08-12 03:49:43

标签: c# asp.net-mvc pagedlist

仅使用@model Project.Models.UserModel时,我可以正常使用TextBoxFor。但是当将其更改为@model PagedList.IPagedList<Project.Models.UserModel>时,我再也无法使用TextBoxFor

Create.cshtml - 如果没有收到错误,我无法使用TextBoxFor

@model PagedList.IPagedList<Project.Models.UserModel>

...
//I'm having a problem with this code
@Html.TextBoxFor(model => model.userid)

...
  

'IPagedList'不包含'user'的定义,并且没有扩展方法'user'接受类型'IPagedList'的第一个参数可以找到(你是否缺少using指令或汇编引用?)

UserController.cs - 我正在返回一个PagedList

public ActionResult Create(string currentFilter, string searchString, int? page)
{
    if (searchString != null)
    {
        page = 1;
    }
    else
    {
        searchString = currentFilter;
    }

    ViewBag.CurrentFilter = searchString;
    var users = from ug in _odb.USR_MSTR
                     select new UserModel
                     {
                         userid = ug.USR_ID,
                         user = ug.USR_DESC,
                         status = (ug.INACTV_DT == null ? "Active" : "Inactive")
                     };

    int pageSize = 10;
    int pageNumber = (page ?? 1);

    ViewBag.UserFilter = GetSelectListItems();  

    return View(users.ToPagedList(pageNumber, pageSize));
}

public JsonResult Save_User(UserModel model)
{
    string _message = string.Empty;
    using (var _odb = new ProjectEntities())
    {
        try
        {
            USR_MSTR usr_master = new USR_MSTR();
            usr_master.USER_ID = Guid.NewGuid().ToString().Remove(20);
            usr_master.USER_DESC = model.user;
            usr_master.CREATE_DT = DateTime.Now;

            _odb.USR_MSTR.Add(usr_master);
            _odb.SaveChanges();
        }
        catch (Exception ex)
        {
            _message = "An error occured.";
            _message = ex.InnerException.Message;
        }
    }
    return Json(true);
}

UserModel.cs - 我的所有文本框都是在这里定义的

public class UserModel
{
    public string userId { get; set; }

    [Display(Name = "User")]
    public string user { get; set; }

    [Display(Name = "Status")]
    public string status { get; set; }

    [Display(Name = "Filter Search By")]
    public int filterSearchBy { get; set; }

    public int filterSearchText { get; set; }
}

1 个答案:

答案 0 :(得分:2)

如果您同时需要(用于创建新用户的文本框和用户列表的用户列表),则应创建具有这2个属性的新视图模型

public class CreateAndListVm
{
  public string UserId {set;get;}
  public IPagedList<CDS.Models.UserModel> Users {set;get;}
}

现在,从“创建”操作中,返回此视图模型的对象,而不是返回分页列表。您应该在返回之前加载Users属性值。

var vm = new CreateAndListVm();
vm.Users = users.ToPagedList(pageNumber, pageSize);
return View(vm);

现在,您的视图应该强烈键入此新视图模型。您可以使用Model.Users属性来呈现用户列表。

@model CreateAndListVm
@using(Html.BeginForm())
{
   <label>New User Id</label>
   @Html.TextBoxFor(s=>s.UserId)
   <input type="submit" />
}
<table>
@foreach (var item in Model.Users)
{
    <tr>
        <td>@item.UserId</td>                     
    </tr>
}    
</table>