检查RouteConfig.cs上的值是否设置为

时间:2015-11-19 09:14:38

标签: c# asp.net asp.net-mvc

只有当我在新闻中进入我的索引时才能使用这个。但如果我进入并且必须知道所有新闻,那么这里的错误就是前进。

  

参数字典包含参数'id'的空条目   方法的非可空类型'System.Int32'   'System.Web.Mvc.ActionResult索引(System.String,Int32)'   'MVCSIte.Controllers.NewController'。可选参数必须是a   引用类型,可空类型,或声明为可选   参数。 Parameternavn:参数

RouteConfig.cs

它应该只是检查一些URL和ID,否则它将不会使用这个。

routes.MapRoute("new", "new/{url}/{id}", new
            {
                controller = "new",
                action = "Index",
                url = UrlParameter.Optional,
                id = UrlParameter.Optional
            });

NyhedController.cs

public class New : Controller
{
    DataLinqDB db = new DataLinqDB();

    // GET: Nyhed / here shows the single news
    public ActionResult Index(string url, int id)
    {
        NyhedPage model = new NyhedPage();

        nyheder nyheden = db.nyheders.FirstOrDefault(x => x.Id == id && x.url == url);
        if (nyheden != null)
        {
            model.NyhedenTitle = new HtmlString(nyheden.title);
            model.NyhedenDeck = new HtmlString(nyheden.deck);
            model.Tekst = new HtmlString(nyheden.tekst);
        }

        List<nyheder> NyhedsList = db.nyheders.Where(x => x.Id != id && x.url != url).OrderByDescending(i => i.Id).Take(4).ToList();
        model.NyhedsList = NyhedsList.ToList();


        return View(model);
    }
}

我想要的是,当我发布新闻时,因为它显示了包含此代码的所有新闻:

//Here it shows all the news
public ActionResult Allenyheder()
    {
        NyhedPage model = new NyhedPage();

        List<nyheder> NyhederIndhold = db.nyheders.Take(12).OrderByDescending(i => i.Id).ToList();
        model.NyhederIndhold = NyhederIndhold.ToList();


        return View(model);
    }

1 个答案:

答案 0 :(得分:0)

  

参数字典包含'MVCSIte.Controllers中方法'System.Web.Mvc.ActionResult Index(System.String,Int32)'的非可空类型'System.Int32'的参数'id'的空条目。 NewController”。可选参数必须是引用类型,可空类型,或者声明为可选参数。 Parameternavn:参数

您看到此错误,因为您的方法签名是:

public ActionResult Index(string url, int id)

无论您在此处发送获取请求的链接是什么,都不包含网址的{id}部分。因为id不可为空,所以必须向其传递值,MVC知道您正在尝试访问此方法,而不是另一个因此错误。您可以修复生成链接的任何内容以包含参数id,也可以使id成为可空的int,或者甚至设置默认值(尽管我认为这不适用于你的方法)。

public ActionResult Index(string url, int? id)
{
    if (!id.HasValue) 
    {
        // Return 404 maybe?
    }
    else 
    {
        // Your existing code
    }  
}

我认为你的问题(来自你的意见)是这样的:

@Html.ActionLink("Nyhed", "Allenyheder", "New")

您需要在id中传递ActionLink参数:

@Html.ActionLink("Nyhed", "Allenyheder", "New", new { id = IdOfNewsYouWantHere })
相关问题