Вопрос

I would like to pass a value from a link to a View and display the fields of the single record on the page.

Lets say I have @Html.ActionLink(item.Title, "Article/"+@item.ID, "News") which outputs /News/Article/1, I would need a Controller called NewsController with a /News/Article View.

I already have the following:

NewsController:

namespace WebApplication1.Controllers
{
    public class NewsController : Controller
    {
        private WebApplication1Entities db = new WebApplication1Entities();
        public ActionResult Article()
        {
            var articleModel = (from m in db.News where (m.Id == 1) && (m.Active == true) select m);
            return View(articleModel);
        }
        [ChildActionOnly]
        public ActionResult LatestNews()
        {
            var latestModel = (from m in db.News where (m.Id != 1) && (m.Active == true) select m);
            return View(latestModel);
        }

}

Not sure if I should use FirstOrDefault() as it can only be one record as the Id is unique, but unsure how to reference item objects inside the View without an IEnumerable list. At present the Id is set to 1 but I would like the recordset to reflect the Id passed.

Not sure what code to put inside the View, Article though, here is what I have so far:

Article.cshtml

@model IEnumerable<WebApplication1.Models.News>

@foreach (var item in Model) {
    ViewBag.Title = @item.Title;   

    <div class="row">
        <article class="span9 maxheight">
            <section class="block-indent-1 divider-bot-2">
                <h2>@item.Title</h2>
                @item.Summary
                @item.Content
            </section>
        </article>
        <article class="span3 divider-left maxheight">
            <section class="block-indent-1">
                <h2>Latest News</h2>
                @{ Html.RenderAction("LatestNews", "News"); }
            </section>
        </article>
    </div>
}

LatestNews.cshtml

@{ Layout = null; }
@model IEnumerable<Shedtember.Models.News>

<ul class="nav sf-menu clearfix">
    @foreach (var item in Model)
    {
        @Html.MenuLink(item.Title, "Article/"@item.ID, "News")
    }
</ul>

This works for Id 1 but this needs to be dynamic.

Any help would be much appreciated :-)

Это было полезно?

Решение

In your RouteConfig class map a route as follows:

routes.MapRoute("Article", "Article/{id}", new {controller = "News", action = "Article"});

then in your Article method you can add and use the id parameter as follows:

    public ActionResult Article(int id)
    {
        var articleModel = (from m in db.News where (m.Id == id) && (m.Active == true) select m);
        return View(articleModel);
    }
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top