whisk
whisk

Reputation: 655

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

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 class="col-8 bg-light ms-2">

<h3  class="text-primary my-3">Auction Info</h3>
<div class="row my-2">          
    <div class="row my-2">          
        <div class="col-6">Current Status</div>
        <div class="col-6 input-group-sm">
            @Model.CurrentStatusName
        </div>
    </div>
    <div class="col-6">New Status</div>
    <div class="col-6"style="padding-left: 0px;">
        
    </div>
</div>

Upvotes: 1

Views: 52

Answers (2)

Ibrahim Mohammed
Ibrahim Mohammed

Reputation: 531

[HttpGet]
    public async Task<IActionResult> UpdateStatus(long auctionId)
    {
        var model = await (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 
                    }).FirstorDefaultAsync();
                  
        return View(model);
    }

Consider using asynchronous method in order not to block UI thread

Upvotes: 1

SBFrancies
SBFrancies

Reputation: 4240

Currently your model object is returning an IQueryable, 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());

Upvotes: 2

Related Questions