Home > Blockchain >  Passing Linq query result to View from controller and Getting Error (error in the question)
Passing Linq query result to View from controller and Getting Error (error in the question)

Time:12-24

Getting Error

The model item passed into the ViewDataDictionary is of type 'Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryable`1[CTA.Web.Areas.Nucleus.Models.UnitStatusUpdateDto]', but this ViewDataDictionary instance requires a model item of type 'CTA.Web.Areas.Nucleus.Models.UnitStatusUpdateDto'.

I should be getting back one result, a string saying "New Item".

I have no clue why this is throwing an error. I get that It says that Im passing two different types but they seem to do the same. This is probably something supper simple but I've spent the last hour looking on SO and google trying to figure out what I'm doing wrong. Controller

    [HttpGet]
    public IActionResult UpdateStatus(long auctionId)
    {
        var model = (from w in _db.WorkFlowStatusType
                    join u in _db.UnitStatusHistory on w.WorkFlowStatusTypeId equals u.CurrentStatus
                    where u.AuctionId == auctionId
                    select new UnitStatusUpdateDto
                    { 
                        CurrentStatusName = w.Name 
                    });
                  
        return View(model);
    }

Model

public class UnitStatusUpdateDto
{
    public string CurrentStatusName { get; set; }
}

View

@model CTA.Web.Areas.Nucleus.Models.UnitStatusUpdateDto

<div >

<h3  >Auction Info</h3>
<div >          
    <div >          
        <div >Current Status</div>
        <div >
            @Model.CurrentStatusName
        </div>
    </div>
    <div >New Status</div>
    <div style="padding-left: 0px;">
        
    </div>
</div>

CodePudding user response:

Currently your model object is returning an IQuerable, to convert to the DTO class from the query you need to use a method that will populate it. Something like this is you only want one object:

return View(model.First());

or this if you may have a null result:

return View(model.FirstOrDefault());
  • Related