[Solved] ASP.Net Core MVC RuntimeBinderException: object does not contain a definition for

AliYilmaz
 
on Jun 07, 2022 11:25 PM
Sample_833630.zip
1564 Views

Hi,

What is the problem here? I get this error.

Error : RuntimeBinderException: 'object' does not contain a definition for 'Tarih'

Controller

public IActionResult ArtikelList(string id)
{
    var artikel = _artikelReadRepository.GetWhere(x => x.BeyannameNO == id)
        .OrderByDescending(x => x.CreatedDate).ToList();
    var a = _beyannameReadRepository.GetWhere(x => x.BeyannameNO == id)
        .OrderByDescending(x => x.CreatedDate).ToList();
 
    var res = (from v in artikel
               join y in a
               on v.BeyannameId equals y.Id
               select new
               {
                   Tarih = y.Tarih 
               }).ToList();
 
    ViewBag.Artikel = res;
 
    return View();
}

View

@foreach (var item in ViewBag.Artikel)
{
    <div class="card mb-2">
        <div class="card-header" id="headingOne">
            <h5 class="m-0">
                <a href="#collapseOne" class="text-dark" data-toggle="collapse" aria-expanded="true" aria-controls="collapseOne">                                       
                    @item.Tarih                                           
                </a>
            </h5>
        </div>
}

 

Download FREE API for Word, Excel and PDF in ASP.Net: Download
dharmendr
 
on Jun 08, 2022 09:11 AM
on Jun 09, 2022 05:21 AM

Hi AliYilmaz,

To fix this error creating a class and return strongly type model instead of anonymous object.

Refer below example.

Database

For this example I have used of Northwind database that you can download using the link given below.

Download Northwind Database

Model

public class Customer
{
    public string CustomerID { get; set; }
    public string ContactName { get; set; }
    public string City { get; set; }
    public string Country { get; set; }
}

Controller

public class HomeController : Controller
{
    private DBCtx Context { get; }
    public HomeController(DBCtx _context)
    {
        this.Context = _context;
    }

    public IActionResult Index()
    {
        var res = (from customer in this.Context.Customers.Take(5)
                    select new CustomerModel { Name = customer.ContactName }).ToList();
        ViewBag.Artikel = res;
        return View();
    }

    public class CustomerModel
    {
        public string Name { get; set; }
    }
}

View

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    @foreach (var item in ViewBag.Artikel)
    {
        @item.Name
        <br />
    }
</body>
</html>

Output

Maria Anders

Ana Trujillo

Antonio Moreno

Thomas Hardy

Christina Berglund