Using list in a model value in LINQ query

前端 未结 2 397
有刺的猬
有刺的猬 2021-01-15 02:07

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

相关标签:
2条回答
  • 2021-01-15 02:46

    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

    0 讨论(0)
  • 2021-01-15 02:55

    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>
    
    0 讨论(0)
提交回复
热议问题