2011-03-20 5 views
0

내보기에서 WebGrid를 사용하여 표를 표시합니다.MVC 3 뷰의 모델에 데이터가 있는지 어떻게 확인할 수 있습니까?

모델에 데이터가 있지만 모델에 데이터가없는 경우 WebGrid에서 예외가 발생하면 예외가 발생합니다.

Model != null하지만 IF 코드 내 코드를 실행하면 확인해 보았습니다. 또한 if (Model.Count() > 2)을 확인하기 위해 수표를 찍어 보았는데 그저 "The specified resource does not exist."이라는 메시지를 전했습니다.

두 조건 중 하나를 사용하면 IF 내부의 코드가 실행됩니다. 모델에 행이 있는지 확인하기 위해 전달되는 정보를 확인할 수있는 간단한 방법이 있습니까?

@model IEnumerable<Selftestware.Storage.Models.TestFormat> 

@section content { 
    <div id="content"> 

    @if ( Model != null) { 

     var grid = new WebGrid(
      source: Model, 
      defaultSort: "Name", 
      canPage: true, 
      canSort: true, 
      rowsPerPage: 20); 

답변

2

당신은 목록 액션 emmty 목록의 예에서 보낼 수 있습니다

public ActionResult List() 
{ 
//hear check if is null 
return View(new List<yourModel>()); 
} 
1
public static class YourWelcome{ 
    public static bool IsNullOrHasNullProperties(this object model){ 
     if(model == null) { 
      return true; 
     } 
     return model.GetType() 
       .GetProperties(BindingFlags.Public|BindingFlags.Instance) 
       .Where(propertyInfo => !propertyInfo.PropertyType.IsValueType) 
       .Any(propertyInfo => propertyInfo.GetValue(model,null) == null); 
    } 
    public static bool IsNullOrEmpty<T>(this IEnumerable<T> enumerable){ 
     return enumerable == null || !enumerable.Any(); 
    } 
    } 
+0

미안하지만 위의 대답은 내 문제에 대해 이해가 가지 않습니다. 면도기 뷰 내에서 모델에 전달 된 데이터가 있는지 확인하고 싶습니다. 테이블에 데이터가없는 경우에는 모델에 전달 된 데이터가 없습니다. 모델이 null인지 확인하려고하면 "리소스를 찾을 수 없습니다"와 같은 메시지가 나타납니다. –

+1

확인. 보기에서'@if (Model! = null)'을'@if (! Model.IsNullOrHasNullProperties()) '로 대체하십시오. 모델의 속성 중 null이 있는지 여부와 Model이 null인지 여부를 확인합니다. 따라서 모델이 null이 아니고 null 속성이없는 경우 데이터가 있습니다. – smartcaveman

1

이 모델이 데이터를 가지고 있지 않은 경우 내 webgrid와 scenaro을 처리하는 방법입니다.

if (Model.Results.Count() > 0) 
{ 

    <div id="grid"> 


     @grid.GetHtml() 

    </div> 
} 
else 
{ 
    <p>No Results Found.</p> 
} 
관련 문제