0

In my controller I do initialization like this:

using mylib.product;
using mylib.factory;

product p = new product();
factory f = new factory(p);

How do I do the same thing using the @model keyword in a partial view?

Thanks

Kyle Trauberman
  • 25,414
  • 13
  • 85
  • 121
River
  • 1,487
  • 3
  • 15
  • 25
  • 2
    What do you want to do? Your question is not clear. – Darin Dimitrov Oct 13 '11 at 20:17
  • I am trying to setup some classes, to obtain content for display. I am exploring the option of using the namespace of these classes in the view. This is more of a Separation of Concern question. What are the technologies available in MVC3 that allows you do this. – River Oct 13 '11 at 22:33

4 Answers4

1

If you are trying to add namespaces/classes to you view, then it's:

@using mylib.product;
1

I should parse the model to the view by

return View("ViewName");

and in the view;

@model Project.Namespace.Class
Rikard
  • 3,828
  • 1
  • 24
  • 39
1

You should use view models:

public class MyViewModel
{
    public string Name { get; set; }
    public string Address { get; set; }
}

which will be passed to the view from the controller action:

public ActionResult Index()
{
    product p = new product(); 
    factory f = new factory(p);   
    var model = new MyViewModel
    {
        Name = p.Name,
        Address = f.Address
    }
}

and then your view will be strongly typed to this view model:

@model MyViewModel
@Html.DisplayFor(x => x.Name)
@Html.DisplayFor(x => x.Address)
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
0

I think you need to transfer more than one instance of different classes to View.(Am I right?) If yes, I suggest to use ViewBag for it. Something like this:

// Controller
=========
product p = new product(); 
factory f = new factory(p);
....
// Add some value for p and f 
ViewBag.Product = p;
ViewBag.Factory = f;
return View();

// View
=========
var p = (product) ViewBag.Product;
var f = (factory) ViewBag.Factory;
// now you have access to p and f properties, for example:
@Html.Label(p.Name)
@Html.Label(f.Address)

Do not forgot that ViewBag is a Dynamic container and you need to Cast it to a type when you want to use its value in View

Amir978
  • 857
  • 3
  • 15
  • 38
  • Yeah, that is the ideal I am toying with. Is there an more elegant way? http://stackoverflow.com/questions/4766062/is-using-viewbag-in-mvc-bad – River Oct 13 '11 at 23:09