2

I am at very basic stage of asp.net MVC development. So sometimes I struggle with simple LINQ queries to work.

scenario-

I have A page that has some Image and comment on that Image by users (Just Like a post on facebook containing comments from users).

So I am saving those comments from the textarea and sending Image ID via Ajax query.

Here Is my controller action method-

Saving comment-

   [HttpPost]
        public void SaveComment(CardModel card) {
            CardCommentTable commenttable = new CardCommentTable();
            commenttable.CardComment = card.cardComment;
            commenttable.FKcardID = card.cardID;
            db.CardCommentTables.InsertOnSubmit(commenttable);
            db.SubmitChanges();
        }

This Comment is saved in CardCommentTable that has foreign key reference of Table in that Image is saved.

Rendering Image and other fields on view page-

This query renders Image and other fields that make it An Image post. Like title, dateofsubmit, Like etc.

public ActionResult CardDetails(CardModel card) {

            var cardDetail = (from u in db.CardTables
                              where u.CardID == card.cardID
                              select new CardModel {
                                  cardID = u.CardID,
                                  cardHashCode = u.CardHashCode,
                                  cardDate = u.CardDate,
                                  cardFileName = u.CardFileName,
                                  cardFilePath = u.CardFilePath,
                                  cardTitle = u.CardTitle
                              }).ToList();
            return View(cardDetail);

        }

Now In cardTable I have one more column named cardComment in that I want to show all those saved comments from table CardCommentTable.

So I tried-

public ActionResult CardDetails(CardModel card) {
        var allsavedcomments= (from u in db.CardCommentTables
                           where u.FKcardID == card.cardID
                           select u).ToList();

        var cardDetail = (from u in db.CardTables
                          where u.CardID == card.cardID
                          select new CardModel {
                              cardID = u.CardID,
                              cardHashCode = u.CardHashCode,
                              cardDate = u.CardDate,
                              cardFileName = u.CardFileName,
                              cardFilePath = u.CardFilePath,
                              cardTitle = u.CardTitle,
                              cardComment = allsavedcomments // Trying to render all saved coments here.
                          }).ToList();
        return View(cardDetail);

    }

View-

@model IEnumerable<FunRanger.Models.CardModel>

@foreach (var item in Model) {
    <script type="text/javascript">
        $(function () {
            $('#save-comment').click(function () {
                var textareavalue = $('#textarea-comment').val();
                $.ajax({
                    url: '/Home/SaveComment/',
                    type: 'post',
                    data: '&cardComment=' + textareavalue + '&cardID=' + '@item.cardID',
                    success: function (data) {
                        $('#all-comments').append(data);


                    }

                });

            });

        });
    </script>
    using (Html.BeginForm()) {
    @Html.ValidationSummary(true)


        @if (Model != null) {


                <h2 class="header-wrapmain">
                    @item.cardTitle
                </h2>

                    @item.cardDate.ToShortDateString()


                        <img src="@item.cardFilePath" />

                                <a href="#" class="@item.cardHashCode" rel="tooltip" data-placement="bottom" title="Filter by @item.cardHashCode">
                                    #@item.cardHashCode</a>



        }
        else {
            <div class="alert alert-danger">
                No More items to preview
            </div>
        }


    }

    <textarea class="span12" rows="5" id="textarea-comment" style="resize: none" placeholder="Enter a comment..."></textarea>

        <a href="javascript:;" id="save-comment" class="btn-primary btn">Save comment</a>

        <ol>
            <li>
                @item.cardComment
            </li>
        </ol>

}

How can I insert List result in a column here.

How do I show all saved comments with this above query?

Thanks for any help.

4
  • Are you talking about displaying the comments in your view? If so, please add the view also. Commented Feb 3, 2014 at 10:59
  • Are you getting an error? What is it and where? cardComment will be whatever type you declared it as. What type is that? Commented Feb 3, 2014 at 10:59
  • @simonatrcl- Yes the error is Error 16 Cannot implicitly convert type 'System.Collections.Generic.List<FunRanger.Models.CardCommentTable>' to 'string' Commented Feb 3, 2014 at 11:06
  • @user3163213, the error tells you that you are trying to display all the comments at once, as if it where a single string object. Commented Feb 3, 2014 at 11:12

2 Answers 2

5

I slightly renovated your code with Foreign key relations ship. This will save your from using two different queries to your database (like what you are doing now).

So if you Database Model looks like this -

enter image description here

Then you should have one viewmodel in your code in this way -

public class ImageViewModel
{
    public string ImageId { get; set; }
    public string ImageUrl { get; set; }
    public List<string> Comments { get; set; }
}

And your controller action which will return all the results should be like this -

 public class ListController : Controller
    {
        public ActionResult Index()
        {
            ImageViewModel model;
            using (SampleEntities entities = new SampleEntities())
            {
                model = (from p in entities.Images
                                     where p.ImageId == "1"
                                     select new ImageViewModel()
                                     {
                                         ImageId = p.ImageId,
                                         ImageUrl = p.ImageUrl,
                                         Comments = p.ImageComments.Select(pa => pa.Comment).ToList()
                                     }).FirstOrDefault();
            }

            return View(model);
        }
    }

Finally the view which will display all the Image results -

@model MVC.Controllers.ImageViewModel

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

<div>
    <h4>ImageViewModel</h4>
    <hr />
    <dl class="dl-horizontal">
        <dt>
            @Html.DisplayNameFor(model => model.ImageId)
        </dt>

        <dd>
            @Html.DisplayFor(model => model.ImageId)
        </dd>

        <dt>
            @Html.DisplayNameFor(model => model.ImageUrl)
        </dt>

        <dd>
            @Html.DisplayFor(model => model.ImageUrl)
        </dd>
        <br/>
        @foreach (var item in Model.Comments)
        {
            @item <br/>
        }

    </dl>
</div>

Output would be -

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

1

Your cardComment property is a list of strings; it needs to be iterated in order to be displayed. Replace:

<ol>
    <li>
        @item.cardComment
    </li>
</ol>

with:

<ol>
@foreach (var singleComment in Model.cardComment)
{
   <li>@singleComment </li>
} 
</ol>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.