0

I am having a problem calling a model property from my view. I may have to create an instance of it in the view.

ERROR MESSAGE: Object reference not set to an instance of an object. However inside the model it works fine.

View:

@model site.Models.modeldata  
     @foreach (System.Data.DataRow row in  Model.DataSets["test"].Tables[0].Rows)
    {
        @:row["id"] 
    }  

Model:

 public IDictionary<string, DataSet> DataSets { get; private set; 
2
  • You should be passing data from your controller to your view. Use ViewBag
    – p.campbell
    Mar 26, 2012 at 20:22
  • Object reference not set to an instance of an object.
    – tdjfdjdj
    Mar 26, 2012 at 20:28

2 Answers 2

1

Your controller should be deciding to include the required data for the view. Refactor to use something other than a dataset.

//build up a collection in the controller
var items = new List<Customer>();
items.Add(new item{ ID = 4, CustomerName="user123"});
ViewBag.items = items;  //pass to the view via ViewBag, a dynamic object

In your view:

@foreach (var item in ViewBag.items)
{
    @:item.ID + " " + item.CustomerName
} 
1

You should initialize the DataSets property in your controller, or better yet, in the constructor of your model. Collection properties shouldn't ever be null unless you have an explicit reason for doing so.

Of course, in this particular case you should also be checking that "test" exists in your dictionary before referencing it.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.