Model binding with view in .NetCore project gives object reference null error --

0

My problem is as you read in the above title -

My project is in .NetCore. Am doing some calculations and returning some value from my controller to the related view. I have used Product as model class in my application.

My controller code -

    [Route("ProductDetail")]
    [HttpGet]
    public IActionResult ProductDetail(int id)
    {
        if(id>0)
        {
            Product pEntity = pService.GetProductById(id);
            if(pEntity!=null)
            {
                ViewData["ProductId"] = pEntity.Id;
                return View("ProductDetail", pEntity);
            }
            else
            {
                return RedirectToAction("Index");
            }
        }
        else
        {
            return RedirectToAction("Index");
        }
    }

razor code for the view -

    @page
    @using System.ComponentModel

    @model CoreSpeechService.App.Model.Product

   @{
      Layout = "~/Pages/Shared/_Layout.cshtml";
    }

   <h1>Dettagli del Prodotto</h1>


   <p style="color:#790bf6">Vedi i dettagli del prodotto:  </p>
   <br /><br />


   <div class="row">
   @if(Model!=null)   < ---- at this line
   {
        bla..blablabla ....
        blablabla ...
        bla ..
        blabla ..
    
   }
   </div>

My error - : 'Object reference not set to an instance of an object.'

    System.NullReferenceException
    HResult=0x80004003
    Message=Object reference not set to an instance of an object.
    Source=CoreSpeechService.App.Views
    StackTrace:
    at CoreSpeechService.App.Pages.Shared.Pages_Shared_ProductDetail.get_Model()

Although data is being clearly returned by the method as confirmed, Model gives null at the inopportune moment of loading it. I experimented with inheriting my Product class from PageModel and again removing it. Apparently, that has no effect either way. I went through the official docs of .netcore on model binding. No apparent anomaly.

Where is the error in this flow? If you need more info from my code/project structure, ask for it.

*** the model class Product

    public class Product
    {
       public int Id { get; set; }

       public string product_code { get; set; }

       public string product_name { get; set; }

       public string product_brief { get; set; }

       public int product_price { get; set; }

       public string product_imageurl { get; set; }

       public string SeoUrl { get; set; }

       public int product_rating { get; set; }

   }
asp.net-core
model-view-controller
.net-core
mvvm
object-reference
asked on Stack Overflow Jul 24, 2020 by Prabir Choudhury • edited Jul 25, 2020 by Prabir Choudhury

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0