简体   繁体   中英

Populating a page with data from a database in mvc 5

I would like to populate certain parts of a view with certain fields from a database. I'm not sure exactly how to make this work. This is my current situation...

Here is my controller action:

public ActionResult Course_page(string id)
    {
        string abbrev = id;
        var cpage = from c in db.Course_page
                    select c;

        if (!String.IsNullOrEmpty(abbrev))
        {
            cpage = cpage.Where(x => x.abbrev.Contains(abbrev));

        }

        return View(cpage);
    }

My Model:

[Table("course_page")]
public class Course_page
{
    [Key]
    public int CourseID { get; set; }
    public string Meta { get; set; }
    public string Title { get; set; }
    public string Country { get; set; }
    public string main_image { get; set; }
    public string list_1 { get; set; }
    public string list_2 { get; set; }
    public string list_3 { get; set; }
    public string list_4 { get; set; }
    public string list_5 { get; set; }
    public string list_6 { get; set; }
    public string list_7 { get; set; }
    public string list_8 { get; set; }
    public string list_9 { get; set; }
    public string list_10 { get; set; }
    public string testim_1 { get; set; }
    public string testim_2 { get; set; }
    public string testim_3 { get; set; }
    public string course_site { get; set; }
    public string popup_script { get; set; }
    public string abbrev { get; set; }
}

The view (shortened):

@model IEnumerable<oltinternational_mvc.Models.Course_page>
<div id="main_container">
<article class="content">
    <h1>{@Html.DisplayNameFor(modelItem => cpage.Title)}</h1>
</article>
</div>

I get that I have to reference the cpage variable somewhere on the view but I'm not sure exactly in what manner. The idea is that the course page will load with the correct details as per the ID provided by the URL.

Please could someone advise me how I am to include the cpage variable in the view file or if I am doing this the correct way at all?

You are doing it correct way just change this helper :

{@Html.DisplayNameFor(modelItem => cpage.Title)} to

@Html.DisplayNameFor(modelItem => modelItem .Title)

And print the data in foreach loop because you can have more than one result.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM