查看模型列表返回空对象



>查看代码:

@using HRHPMVS.Models
@model HRHPMVS.ViewModel.NationalityVM
@{
    ViewBag.Title = "list";
    //Layout = "~/Views/Shared/OrangeHR.cshtml";
    Layout = null;
}
<h1>Details</h1>
<div>
    <h1>Details</h1>
    <div>
@if (Model.NationalitiesList != null)
{
      foreach (var item in Model.NationalitiesList)
      {
         @Html.DisplayFor(m => item.Code) 
      }
}
    </div>
</div>

控制器代码:

public ActionResult list()
{
    ModelState.Clear();
    NationRepObj.list();
    return View();
}

型:

namespace HRHPMVS.Models
{
    public class Nationality
    {
        public int ID { get; set; }
        [Display(Name = "Name")]
        [Required(ErrorMessage = "Name is Requirde")]
        [RegularExpression(@"^[a-zA-Z]+$", ErrorMessage = "please: Use letters only ")]
        public string Name { get; set; }
         [Display(Name = "Code")]
        [Required(ErrorMessage = "Code is Requirde")]
        [RegularExpression(@"[0-9]*.?[0-9]+", ErrorMessage = "{0} must be a Number.")]
        [Range(0, int.MaxValue, ErrorMessage = "Please: enter valid integer Number")]
        public int Code { get; set; }
        public Nullable<short> IsActive { get; set; }
        // ...
    }
}

视图模型:

namespace HRHPMVS.ViewModel
{
    public class NationalityVM
    {
        public Nationality Nationality { get; set; }
        public List<Nationality> NationalitiesList { get; set; }
        // ...
    }
}

视图模型列表:

namespace HRHPMVS.ViewModel
{
    public class NationalityVMList
    {
      public List<NationalityVM> Nationalities {get;set;}
      // ...
    }
}

功能:

public   void  list()
{
    List<Nationality> n = new List<Nationality>();
    Nationality nt = new Nationality { Code=1,Name="doodoo",ID=1,IsActive=1};
    NationalityVM vm = new NationalityVM ();
    List<NationalityVM> l1 = new List<NationalityVM>();
   // foreach(var itm in nt)
    n.Add(nt);
    if (vm.NationalitiesList == null)
    {
        vm.NationalitiesList = new List<Nationality>();
        vm.NationalitiesList.Add(nt);
    }
}

我试图在视图中查看详细的国籍。我想从列表视图模型查看它,但我失败了。我使视图模型列表指向视图模型,视图模型指向模型,但是当我尝试将国籍添加到列表中时,返回带有错误Null reference exception wasn't handled in user code的空值。

我想从视图模型列表中显示国籍详细信息

此代码存在几个问题,很难知道您要实现的目标。

你有一个名为"viewmodellist"的类,名为NationalityVMList。我不相信这是有目的的。也许删除它。

您的视图需要 NationalityVM 类型的模型,但您的控制器操作不会向其传递任何内容。

您的"函数"创建一个列表以及几个未使用的变量,并且不返回任何内容。

更改控制器,使其将模型传递给视图:

public ActionResult list()
{
    NationalityVM model = NationRepObj.GetNationalityVM();
    ModelState.Clear();
    return View(model);
}

将函数更改为:

public NationalityVM GetNationalityVM()
{
    NationalityVM vm = new NationalityVM();
    Nationality nt = new Nationality { Code=1,Name="doodoo",ID=1,IsActive=1};
    vm.NationalitiesList = new List<Nationality>();
    vm.Add(nt);
    return vm;
}

希望这会得到一些工作。

相关内容

  • 没有找到相关文章

最新更新