3

I have created some Razor code to output images onto a page if the exist. It is detailed below and contains some simple checks to prevent rendering a blank list item. The site has gone live and works fine. The client then deleted the image from the media folder within Umbraco, meaning my node had a valid image assigned but the image just didn't exists. I got the following exception:

'string' does not contain a definition for 'crops'

How do I deal with this?

@using umbraco.MacroEngines;
@inherits umbraco.MacroEngines.DynamicNodeContext
@using umbraco.presentation.nodeFactory
@using umbraco.cms.businesslogic.media

<ul>
    @foreach (dynamic client in @Model.Children)
    {
        var image = Model.MediaById(client.Logo);
        var crops = image.imageCropper.crops;

        <li>
            <h2><span>@client.Name</span></h2>

            @if (crops != null || crops.GetType().ToString() != "System.String")
            {
                <span class="itemImage">
                    <img src="@crops.Find("@name", "cropname").url" alt="@client.Name" />
                </span>
            }
        </li>
    }
</ul>
4

2 回答 2

0

在这种情况下,您可能需要进行类型检查。我相信 MediaById 方法应该返回一个 DynamicNode 如果它是有效的,所以应该像下面这样工作:

if(image.GetType() == typeof(DynamicNode))
{
    ...
}
于 2012-05-16T03:34:19.277 回答
0

我遇到了这个问题。我发现,如果 Media 已被删除(并且过去已被选中),则 Model.MediaById(imageid) 调用将引发异常。

所以我像这样设置我的测试:

dynamic mainMediaImage = new DynamicNull();
try
{
  mainMediaImage = Model.MediaById(related.eventMainImage);
}
catch(Exception e)
{
  <p style='display: none;'>@e.Message</p>
}
var cropUrl = "";

if(mainMediaImage.GetType() == typeof(DynamicMedia))
{  
   cropUrl = GetImageCropperUrl(Model.MediaById(related.eventMainImage).crops, "List Image");    
}       

我仍然收到错误,但它不会显示给用户。

我发现它永远不会进入我的 DynamicMedia 检查,所以我必须在调用周围添加 try...catch() ,否则整个宏将失败。

于 2013-01-30T17:12:34.430 回答