簡體   English   中英

如何在asp.net mvc中使用自定義操作生成自定義URL

[英]how to generate a custom url with custom action in asp.net mvc

我是Web開發和asp.net mvc的新手,我正在嘗試創建一個博客作為我的第一個項目。

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

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

當然必須有其他方式。 在這個問題上的一點指導會有所幫助。

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

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

在這里,我指定了一個名為title的附加URL參數,以使URL更加SEO友好(例如“/ posts / 1 / Hello%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>

希望這能為您澄清一些事情。

您將在操作方法中使用一個參數來標識實際的博客帖子。

例如:

/post/view/123

會查看ID為123的博客文章。您對PostController的操作看起來像

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

所以你只需要一個控制器,在這個例子中有一個動作來完成所有這些。 只是參數改變了。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM