Penguen
Penguen

Reputation: 17288

How to fill list using Mvc 3 razor?

I am a new in Asp.net Mvc3. How can I show list using Test method but I can not write @product.Test().

VIEW:


@model IList<MvcApplicationScottGu.Models.ProductModel>

@{
    Layout = "~/Views/Shared/_Layout.cshtml";
    ViewBag.Title = "Product";
}

<h2>Product</h2>
<ul>
@foreach (var product in Model)

      <li>@product.Test()</li>

</ul>

CONTROLLER:


namespace MvcApplicationScottGu.Controllers
{
    public class ProductController : Controller
    {
        //
        // GET: /Product/

        public ActionResult Test()
        {
            var products = new ProductModel().GetProduct();
            return View("Product",products);
        }

    }
}

Upvotes: 1

Views: 11246

Answers (5)

wayne.blackmon
wayne.blackmon

Reputation: 761

I will show you how to do this using the Entity Framework 4.1 code first method. first the model

namespace MvcApp.Models
{
    public class Product
    {
        public int ProductId { get; set; }
        public string Name { get; set; }
        public decimal Price { get; set; }
        public string Description { get; set; }
    }
}

Now the context.

using System.Data.Entity;

namespace MvcApp.Models
{
    public class MyAppContext : DBContext
    {
        public DBSet<Product> { get; set; }
    }
}

Now initialize the database

namespace MvcApp.Models
{
    public class MyAppContextInitializer : DropAndCreateAlways<MyAppContext>
    {
        protected override void Seed(MyAppContext context)
        {
            Product product = new Product
            {
                Name = "Widget",
                Price = 10.00m;
                Description = "It's a widget!"
            };
            context.Products.Add(product);
            base.seed(context);
        }

    }
}

Now add the following line to the Application_Start() method of Global.asax.cs.

Database.SetInitializer(new MvcAppContextIntializer());

You now have a database with one record of data in it. Back to MVC. First the controller and action method. You should create the controller and action method first, not the other way around.

namespace MvcApp.Controllers
{
    public class ProductController : Controller
    {
        DBContext dbContext = new DBContext();

        //
        // GET: /Product/

        public ViewResult List()
        {
            IEnumerable<Product> products = dbContext.Products;
            return View(products);
        }

    }
}

Now right-click on the List action method and select Add View. Be sure and name the view "Test" or something like a more descriptive "List". Do not use a scaffolding template. Check "Create strongly typed view" and type IEnumerable in the "Model class:" field. The view file List.cshtml will be placed in the Views\Product folder. Add the folloing markup and razor code.

@model IEnumerable<MvcApp.Models.Product>

@{
    Layout = "~/Views/Shared/_Layout.cshtml";
    ViewBag.Title = "List of Products";
}

<h2>Product List</h2>
<ul>
    @foreach (var p in Model)
    {
        <li>@p.Name></li>
        <li>@p.Description</li>
        <li>@p.Price</li>
    }
</ul>

Assuming that you have a HomeController with an Index action method, the application will launch. Add Product/List to the site url and hit enter. Your view should load. I hope this helps.

Upvotes: 1

awrigley
awrigley

Reputation: 13581

If you fight MVC, MVC won't win, but you will lose

The problem is that you are trying to call an action from a View. Which means you seriously aren't getting MVC. It means you are trying to use an MVC view as if it was a Web Form.

Views in MVC are just templates for stuffing full of nicely formatted data that the user can easily digest.

MVC vs Web Forms - Tale of Two Christmas Requests

Lets use a seasonal analogy.

Tale of an MVC Request:

In MVC, a view is like your Christmas turkey. The turkey gets stuffed with data and is served to the user.

The Controller is like the cook. The family ask him for a turkey and he cooks it and serves it for Christmas dinner. To cook the turkey, the cook must first get it from the store. The store where the cook buys the turkey is the Model.

The whole process sort of makes sense.

Tale of an ASP.NET Web Forms Request:

In ASP.NET Web Forms, the situation is different.

Again, the family wants Turkey for their Christmas dinner. Instead of using a cook, they do something highly improbably:

Instead of asking the cook, the family asks the turkey.

The turkey says "OK" (or rather, "Gobble, goggle, gobble"). It then kills itself, plucks itself, cooks itself and, if it hasn't exploded in the microwave, a burnt offering is served to the family (user).

Instead of being stuffed with lots of lovely well cooked data, it is stuffed with an unappetising and indigestible goo called ViewState, which is sort of like an astronaut's Christmas dinner.

The dinner is so disgusting that the merry festive gathering dissolves into mayhem and someone sets fire to Father Christmas who is still stuck up the chimney (he ate too many mince pies).

Rudolph, meanwhile, has naffed off back to Lapland so that he can recover in time for the rutting season, which is sort of like his Christmas.

Merry Christmas everyone (or at least, those of you who are into Christmas).

Upvotes: 11

Chase
Chase

Reputation: 564

You've passed the Product model to the view so you don't have to call the controller action inside the view. Simply use

@product.PropertyNameHere

Intellisense, if you have it enabled, should auto-populate a list of options as soon as you type @product. .

You'll also want to make sure you bracket around your foreach although I'm not entirely sure it's necessary... I think it is.

@foreach (var product in Model)
{
<li>@product.Whatever</li>
}

Upvotes: 1

Vasiliy R
Vasiliy R

Reputation: 941

You don't have to call that Test() method in a View ever.

Your Model property in the View is what you pass as a second parameter here:

return View("Product", products);

So, basically, products variable at Controller level becomes Model at your View. By the time View actually being rendered, the ProductController.Test() method is already called (in fact, this call is what makes the View even rendering).

Upvotes: 3

Dennis Traub
Dennis Traub

Reputation: 51634

What exactly happens when you try? Can we see your Test() method?

Have you tried enclosing the list item generation with brackets like this?

<ul>
@foreach (var product in Model)
{
  <li>@product.Test()</li>
}
</ul>

Upvotes: 0

Related Questions