Reputation: 6776
I am new to both Web development and asp.net mvc and i am trying to create a blog as my first project.
Now as is the norm that in blogs every post has its own page(sort of like stackoverflow having a new page for each question). But i am having a hard time comprehending that how i am going to achieve this.
Because for example every new page must have its own view and its own action method. Now suppose if there are 1000 blogposts that would that mean 1000 views and 1000 actions in the controller being created dynamically.
Surely there must be some other way. A little guidance in this matter would help alot.
Upvotes: 1
Views: 1735
Reputation: 5128
You will only have one action and one view, but different data (view model) for different blog posts. So, for example, let's say you declare a special route for your blog posts:
routes.MapRoute(
"BlogPostDetails",
"posts/{id}/{title}",
new { controller = "Posts", action = "Details" }
);
Here I'm specifying an additional URL parameter called title
to make URLs more SEO-friendly (e.g. "/posts/1/Hello%20world").
Next thing is to define a model and controller:
// /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
}
}
And finally this is how your view (/Views/Posts/Details.cshtml) should look like:
@model [Root namespace].Models.BlogPost;
<article>
<h2>@Model.Heading</h2>
<p>@Model.Text</p>
</article>
Hope this clarifies things a bit for you.
Upvotes: 2
Reputation: 2726
You'll have a parameter to your action method that identifies the actual blog post.
So for example:
/post/view/123
would view blog post with ID 123. Your action on PostController would look like
ViewResult View(int postId){
//get from db, return appropriate content via view here
}
So you only need one controller, and one action in this example to do all this. Just the parameter changes.
Upvotes: 1