skip to Main Content

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);
        }

2

Answers


  1.     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);
        }
    
    Login or Signup to reply.
  2. You are returning list of objects, and view expects a single object.
    You should, either change your controller to something like this, to return single object:

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

    or change model to @model IEnumerable<SixthApp.Models.Customer> and loop trough it on a view to show all objects you got from controller….

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search