2013-11-28 35 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_它是如何回答問題的。提供這種附加背景將顯着提高其長期價值。請[編輯]您的答案以添加解釋,包括適用的限制和假設。 –