ASP.NET MVC null模型传递给控制器​​动作

时间:2011-03-31 17:41:09

标签: asp.net asp.net-mvc

为什么将null参数传递给以下控制器操作?

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

从以下部分视图:

<%@ 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 个答案:

答案 0 :(得分:6)

你不能发送像这样的复杂对象:

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

只有简单的标量属性:

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

在这种情况下,一个好的做法是只发送一个id:

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

然后让你的控制器操作从存储的任何地方获取相应的模型给出这个id:

public ActionResult GetImageForArticle(int id) 
{             
    ArticleSummary article = _someRepository.GetArticle(id);
    if (article == null || !article.ContainsValidThumbNail()) 
    {
        return null;            
    }
    return File(article.ThumbNail, article.ThumbNaiType);
}