4

Why is a null parameter being passed to the following controller action?

 public FileContentResult GetImageForArticle(ArticleSummary article) 
        {             
            if (article == null || !article.ContainsValidThumbNail()) return null;            
            return File(article.ThumbNail, article.ThumbNaiType);
        }  

from the following partial view:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<IEnumerable<AkwiMemorial.Models.ArticleSummary>>" %>
<%if (Model.Count() > 0)
  { %>
<table>    
    <% foreach (var item in Model)
       { %>    
        <tr>                        
             <td>  
               <img src='<%=Url.Action("GetImageForArticle", "Resources", new { article = item })%>' alt=""/>                                
            </td>
        </tr>

    <% } %>

    </table>

1 Answer 1

7

You cannot send complex objects like this:

<%=Url.Action("GetImageForArticle", "Resources", new { article = item })%>

Only simple scalar properties:

<%=Url.Action("GetImageForArticle", "Resources", new { 
    Id = item.Id,
    Foo = item.StringFoo,
    Bar = item.IntegerBar
})%>

So a good practice in this case is to only send an id:

<%=Url.Action("GetImageForArticle", "Resources", new { id = item.Id }) %>

and then have your controller action fetch the corresponding model from wherever it is stored give this id:

public ActionResult GetImageForArticle(int id) 
{             
    ArticleSummary article = _someRepository.GetArticle(id);
    if (article == null || !article.ContainsValidThumbNail()) 
    {
        return null;            
    }
    return File(article.ThumbNail, article.ThumbNaiType);
}  
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.