2013-11-28 31 views
0

所有进出口试图做的就是我的网址有blogid追加到它很像下面...MVC4剃须刀 - 试图让ID在URL的博客文章

http://localhost/blog/blogpost/17

这里我的控制器......

public ActionResult BlogList(){ return View(_repository); } 


    public ActionResult BlogPost(string id) 
    { 
     ViewData["id"] = id; 
     if (ModelState.IsValid) 
     {    

      return RedirectToAction("BlogPost", new { id = id }); 

     } 
     return View(_repository); 
    } 

现在,这里是我的route.config图路线

routes.MapRoute(
      "MyBlog", // Route name 
      "blog/{action}/{id}", // URL with parameters 
      new { controller = "Blog", action = "blogpost", id = 
       UrlParameter.Optional } // Parameter defaults 
     ); 

现在我可以摹等我点击博客列表中的博客时出现的网址。该页面不显示博客,它显示重定向循环消息。如果我省略以下代码...

if (ModelState.IsValid) 
     {    

      return RedirectToAction("BlogPost", new { id = id }); 

     } 

然后我可以显示博客。该网址不会有id值。像这样...

http://localhost/blog/blogpost/

我在做什么错?

+0

更新了我的答案 –

+0

任何人都可以在这方面帮助?我完全失去了这一点。人们不断给我答案,我不明白为什么。任何人都可以给我详细的信息或解释为什么我不能附加一个ID到我的URL像上面。我被告知删除我无法做的BlogList,因为它正在使用中。 – user3036965

回答

0

下面的代码应该与你的工作路线:

// http://localhost/blog/bloglist 
public ActionResult BlogList() 
{ 
    return View(_repository); // show all blog posts 
} 

// http://localhost/blog/blogpost/1 
public ActionResult BlogPost(int? id = null) 
{ 
    if (id.HasValue == false || id.Value < 1) 
    { 
    // redirect to 404 page or BlogList 
    throw new NotImplementedException(); 
    } 
    var blogPostObj = _repository.Find(id.Value); 
    if (blogPostObj == null) 
    { 
    // again redirect to 404 
    throw new NotImplementedException(); 
    } 
    return View(blogPostObj); 
} 
0

删除其采用0参数

public ActionResult BlogList(){ return View(_repository); } 

这不是必须的,因为你的ID是string类型可以是空的BlogList()

下面的代码可以帮助你

public ActionResult BlogPost(string id) 
{ 
    var model=new ModelObject(); 
    if(id!=null) 
    { 
    var model=Blogs.Find(id); //find it from repo 
    return View(model); 

    } 
    return View(model); 
    } 
0

从您的代码看,它看起来不像id字段是可选的。所以我会改变路线。

routes.MapRoute(
     "MyBlog", // Route name 
     "blog/blogpost/{id}", // URL with parameters 
     new { controller = "Blog", action = "blogpost" }, 
     new { id = @"(\d)+"} //ensures value is numeric. 
    ); 
0
RouteData.Values["id"] + Request.Url.Query 
+0

虽然这段代码可能有助于解决问题,但它并没有解释_why_和/或_how_它是如何回答问题的。提供这种附加背景将显着提高其长期价值。请[编辑]您的答案以添加解释,包括适用的限制和假设。 –