Search code examples
asp.netasp.net-coreasp.net-mvc-4razorblazor

I got Error An unhandled exception occurred while processing the request


i'm newly learning ASP.net Core and i got this error :

enter image description here

I have been searching the solution i internet but didn't get any result. Can anyone help me? this is my code:

Details.cshtml

@model SixthApp.Models.Customer

@{
    ViewData["Title"] = "Details";
}

<h1>Details</h1>

<div>
    <h4>Customer</h4>
    <p>@ViewData["data"]</p>

    <hr />
    <dl class="row">
        <dt class = "col-sm-2">
            @Html.DisplayNameFor(model => model.CustomerId)
        </dt>
        <dd class = "col-sm-10">
            @Html.DisplayFor(model => model.CustomerId)
        </dd>
        <dt class = "col-sm-2">
            @Html.DisplayNameFor(model => model.Name)
        </dt>
        <dd class = "col-sm-10">
            @Html.DisplayFor(model => model.Name)
        </dd>
        <dt class = "col-sm-2">
            @Html.DisplayNameFor(model => model.Address)
        </dt>
        <dd class = "col-sm-10">
            @Html.DisplayFor(model => model.Address)
        </dd>
        <dt class = "col-sm-2">
            @Html.DisplayNameFor(model => model.MobileNo)
        </dt>
        <dd class = "col-sm-10">
            @Html.DisplayFor(model => model.MobileNo)
        </dd>
    </dl>
</div>
<div>
    @Html.ActionLink("Edit", "Edit", new { /* id = Model.PrimaryKey */ }) |
    <a asp-action="Index">Back to List</a>
</div>

this is detail method in CustomerController.cs

        public IActionResult Details(int? Id)
        {
            var DataCustomer = _conn.tabel_customer.Where(c => c.CustomerId == Id).ToList();

            return View(DataCustomer);
        }

Solution

  •     public IActionResult Details(int? Id)
        {
            var DataCustomer = _conn.tabel_customer.Where(c => c.CustomerId == Id).ToList();
    
            return View(DataCustomer);
        }
    

    The type your view needs is a model, and what you return to the view in your action is a list

    Try below code:

        public async Task<IActionResult> Details(int? Id)
        {
            var DataCustomer =  await _conn.tabel_customer.FirstOrDefaultAsync(c => c.CustomerId == Id);
    
            return View(DataCustomer);
        }