简体   繁体   中英

Using list in a model value in LINQ query

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.

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 -

在此处输入图片说明

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 -

在此处输入图片说明

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>

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