如果在View的Razor代码中进行空检查后发生NullReferenceException,如何检查变量是否已分配

时间:2017-06-05 05:03:16

标签: javascript c# razor nullreferenceexception

  

我试图通过附加一些我从Linq获得的文本来检查复选框时更改div元素的内容,但是在将列表分配给m时我得到NullReference异常。代码如下。有什么问题?

 onchange = "if(this.checked){
 @ {
   string s = "h";
   string w = "";

   var r = from c in Model.Roles.Keys
   from a in Model.AllRoles
   where a.Name == c select a;
   List < AspNetRoles > m = new List < AspNetRoles > ();
   if (r != null) { **
     m = r.ToList();
   } **
   if (r.Count() != 0) {

     foreach(AspNetRoles role in r) {
       foreach(AspNetUsers user in role.AspNetUsers) {
         Model.Hashset.Add(user);
       }
     }
     foreach(AspNetUsers us in Model.Hashset) {
       s += us.UserName + ',';
     }
     w = s;
   }
 }

 $('#users').append('@w');
 }                                          

0 个答案:

没有答案