0

Model::::

 public class Model1

    {

        public string Name { get; set; }

        public string ProductName { get; set; }

    }

ViewModel::::

public class ViewModel1

    {

      public  List<Model1> model1;

    }

controller:::::::::

var sent = entities.Table1.Where<Table1>(o => o.SenderUserId == userId );

          ViewModel1 newViewModel = new ViewModel1();

            foreach (Table1 gf in sent)

            {

                var nmodel = new Model1();

                nmodel.Name = gf.Name;

                nmodel.ProductName = doSomething(gf.ProductName);

               // **Here I'm stuck====how do I add nmodel to newViewModel**

               //**newViewModel.Add===does not work**

            }

          return View(newViewModel);
2
  • Are you getting a null reference exception? Can you be more clear about "does not work"? Commented Jan 3, 2011 at 5:04
  • I do not get 'Add' as the viewModel does not have an add method. Commented Jan 3, 2011 at 5:10

2 Answers 2

1

A quick guess based on the code you posted, is that you never instantiated the collection.

public class ViewModel1
{
    List<Model1> model1;
    public ViewModel1()
    {
        model1=new List<Model1>();
    }
}
......
newViewModel.model1.Add(nmodel);
Sign up to request clarification or add additional context in comments.

5 Comments

Sorry, I changed the code, its actually public List<Model1> model1;
Yes, I see that it's public, You still need to instantiate it somewhere before you can call Add. I added the correct syntax to add to it.
Thanks a lot, I have a feeling this will work, just another thing: var sent = entities.Table1.Where<Table1>(o => o.SenderUserId == userId ) will sometimes give me null values.
y, I know, should i ask it in a diff question, thisis the first time I'm using stackoverflow
Yes that makes the most sense to me in this instance. However, if it SHOULD ALWAYS return something, then a better practice might be to throw an exception.
1

Change your ViewModel as follows ViewModel::::

public class ViewModel1
{
    public  List<Model1> model1 = new List<Model1>();
}

Change your controller as follows:

var sent = entities.Table1.Where<Table1>(o => o.SenderUserId == userId );
ViewModel1 newViewModel = new ViewModel1();
foreach (Table1 gf in sent)
{
        var nmodel = new Model1();
        nmodel.Name = gf.Name;
        nmodel.ProductName = doSomething(gf.ProductName);
        newViewModel.model1.Add(nmodel);
}

return View(newViewModel);

1 Comment

y, that is what brook said, though ur answer will be more clear to new people, just add '()'in the viewmodel, thanks for your reply

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.