4

It is working with ViewData and ViewBag but try to strongly type model binding that unable to build Model type reference

What I am missing anyone and doing anything wrong.

View:

@model  Working_with_Views.Models.Product;
@{
  var product  = Model;
}
<h3>Name: @product.Title</h3>
<h2>Price: @product.Price</h2>
<h5>Produce Date: @product.ProduceDate</h5>

view page compile time error

Model:

namespace Working_with_Views.Models
{
    public class Product
    {
        public int ProductId { get; set; }
        public string ImgePath { get; set; }
        public string Title { get; set; }
        public DateTime ProduceDate { get; set; }
        public DateTime  LeftDateExpire { get; set; }
        public decimal Price { get; set; }
    }
}

Controller:

 public ActionResult Index()
    {

        Product product = new Product()
        {
            Title = "Pepsi",
            Price = 30.00m,
            ProduceDate = DateTime.Now,
            LeftDateExpire = DateTime.Now.AddDays(7),
        };

        return View(product);
    }
Quiet Islet
  • 536
  • 1
  • 8
  • 28

1 Answers1

0

Passing a model to the view or using it via ViewBag and ViewData is two totally different ways of doing the same thing. The ways of implementing each is very different.

In your case you are incorrectly passing the model to the view - as a matter of fact you are not even passing it through. You are only specifying where the model can be found. You need to specify the whole namespace including the model name, in your case Product:

@model Working_with_Views.Models.Product

Now that you have passed the model to the view now you can use like you want.

Using the below is not convenient because how will the view know that your model is Product if you do not specify it? What happens if there are other models like Customer, Address, Country, etc? How does your view know it has to use Product?

@model  Working_with_Views.Models;

This is why you need to specify to the view the model that you are wanting to use.

You do not even need this part because you can use the model directly:

@{
     var product  = Model;
}

Removing the above mentioned code you can use the model that was passed in by the controller like this:

<h3>Name: @Model.Title</h3>
<h2>Price: @Model.Price</h2>
<h5>Produce Date: @Model.ProduceDate</h5>

I hope this clarifies things a bit more for you when using models in the view.

Brendan Vogt
  • 25,678
  • 37
  • 146
  • 234