2013-03-16 66 views
1

我對Web開發和asp.net mvc都很陌生,我正在嘗試創建一個博客作爲我的第一個項目。如何使用自定義動作在asp.net中生成自定義網址mvc

現在,在博客中每個帖子都有自己的頁面(有點像每個問題有一個新頁面的stackoverflow)的規範。但我很難理解我將如何實現這一目標。

因爲例如每個新頁面都必須有自己的視圖和自己的操作方法。現在假設有1000個博客帖子,這意味着動態創建控制器中的1000個視圖和1000個動作。

當然必須有其他方法。在這個問題上的一點指導將有助於很多。

回答

2

您將只有一個操作和一個視圖,但不同的博客文章有不同的數據(視圖模型)。因此,舉例來說,假設你聲明一個特殊的路徑爲您的博客帖子:

routes.MapRoute(
    "BlogPostDetails", 
    "posts/{id}/{title}", 
    new { controller = "Posts", action = "Details" } 
); 

這裏我指定稱爲title額外的URL參數,使網址更加SEO友好(如「/職位/ 1 /你好%20world「)。

接下來的事情是定義一個模型和控制器:

// /Models/BlogPost.cs 
public class BlogPost 
{ 
    public string Heading { get; set; } 
    public string Text { get; set; } 
} 

// /Controllers/PostsController 
public class PostsController : Controller 
{ 
    public ActionResult Details(string id) 
    { 
     BlogPost model = GetModel(id); 

     if (model == null) 
      return new HttpNotFoundResult(); 

     return View(model); 
    } 

    private BlogPost GetModel(string blogPostId) 
    { 
     // Getting blog post with the given Id from the database 
    } 
} 

最後,這是你的看法(/Views/Posts/Details.cshtml)應該如何看起來像:

@model [Root namespace].Models.BlogPost; 

<article> 
    <h2>@Model.Heading</h2> 
    <p>@Model.Text</p> 
</article> 

希望這爲你澄清了一些事情。

1

您將爲您的操作方法指定一個實際博客文章的參數。

因此,例如:

/post/view/123 

會查看博客文章ID爲123.您對PostController的動作看起來就像

ViewResult View(int postId){ 
    //get from db, return appropriate content via view here 
} 

所以,你只需要一個控制器,並且在這個例子中一個動作做這一切。只是參數改變。

+0

和客戶的uri(像每個問題一樣的stackoverflow)? – 2013-03-16 11:18:19

+0

您會注意到,如果您刪除SO URL的最後一位(離開int ID),它仍然有效。最後一點主要是在那裏搜索引擎優化,並沒有對路由的影響。爲了在自己的應用中製作類似的功能,您需要在路由中使用通配符。請參閱此問題中的{* pathInfo}位以瞭解如何完成:http://stackoverflow.com/questions/10344986/mvc3-routing-basics。請注意,如果您只輸入int id位,則會將您重定向到完整的URL。它根據int id從數據庫中獲得標題,並進行重定向。這樣就有了一個「規範」的url。 – Nik 2013-03-16 13:01:40