user2067567
user2067567

Reputation: 3803

MVC controller view binding

Am new to MVC and am trying below scenario but am struck how to proceed.

In my webpage i have several section and each section has comments below it. and for fetching the comments i have written a function inside the controller as below

public ActionResult ShowPreviousComments()
        {
            Comments com = new Comments();

            LstComments savedComments = new LstComments();

            ///Entity code here


            foreach (var item in comments)
            {
                com.comments = item.Comments;
                com.dTime = item.Time;

                savedComments.lstCommet.Add(com);

            }

            return View();
        }

and model data below so i can get the list in the view

public class Comments
    {
        public string comments { get; set; }

        public DateTime? dTime { get; set; }

        public int airPortId { get; set; }

    }

    public class  LstComments
    {
        public List<Comments> lstCommet { get; set; }
    }

My doubt is how i can hit the controller during the pageload for each sections ?

Sorry if it sounds silly or some error. Please post if i can do it in a better way

Thanks

Upvotes: 0

Views: 5396

Answers (2)

sam rodrigues
sam rodrigues

Reputation: 580

Maybe U can try a script to call the controller on load of the sections of the view

Upvotes: 0

AliRıza Adıyahşi
AliRıza Adıyahşi

Reputation: 15866

controller

public ActionResult ShowPreviousComments()
{
    Comments com = new Comments();
    LstComments savedComments = new LstComments();

    ///Entity code here


    foreach (var item in comments)
    {
        com.comments = item.Comments;
        com.dTime = item.Time;

        savedComments.lstCommet.Add(com);
    }

    return PartialView(savedComments);
}

View

@Html.Action("ShowPreviousComments", "SomeController") 

From My Perspective

controller

public ActionResult ShowPreviousComments()
{
    // Entity code here
    // var comments = entity.comments;

    return PartialView(comments);
}

Index.cshtml (Main view that contains own contents and comments)

// some main view content

// main view comments...
@Html.Action("ShowPreviousComments", "SomeController")

ShowPreviousComments.chtml (partial view that hold the previous comments)

@model IEnumerable<comments>

<div class="comments_container>
    foreach(var item in Model)
    {
        <div class="comment_body">@item.Comments</div>
        <div class="comment_time">@item.Time</div>
    }
</div>

Upvotes: 4

Related Questions