2016-02-29 72 views
1

無法在我的MVC項目中傳遞url參數給我的方法。 目前遇到了以下錯誤:C#MVC - 將URL參數傳遞給方法

The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult SinglePost(Int32)' in 'mybloggywog.Controllers.PostController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.

呼叫低於:

@{ 

    foreach (var article in ViewBag.DisplayPosts) 
    { 
     <a class="ArticleLink" href="@Url.Action("SinglePost", "Post", article.Id)">@article.Title</a> 
     <p>@article.CreatedOn</p> 
     <br/> 
    }  
} 

Routeconfig:

routes.MapRoute(
      "Post", 
      "post/{id}", 
      new { controller = "Post", action = "SinglePost", id = UrlParameter.Optional } 
      ); 

和方法:

public ActionResult SinglePost(int id) 
    { 
     var entities = new blogEntities(); 

     var post = entities.Set<Post>(); 

     var postToDisplay = (from p in post 
          where p.Id == id 
          select p); 

     ViewBag.SinglePost = postToDisplay; 

     return View(); 
    } 

回答

1

嘗試將其更改爲一個anonymo我們的對象:

@Url.Action("SinglePost", "Post", new { id = article.Id }) 
+0

這工作完美。我還不能祝福,但我向你致敬,先生。 –