2

I have been following

http://pluralsight.com/training/Courses/TableOfContents/mvc4-building

to learn some MVC C# for my Company, btw completely amazing Video.

I am populating a View with a SQL source.

In Debug I can definitely tell all my connections work, and I get to my foreach loop that should display all the data in that table

On my @Foreach( var item in Model ) it throws the NullRefException on my Model... here's the code I have

this is my complete view

@model IEnumerable<OilNGasWeb.ModelData.Clients>

@{
    ViewBag.Title = "CLS-Group";
}


@foreach(var item in Model)

{
    <div>
        <h4>@item.Client</h4>
        <div>@item.Address</div>
        <div>@item.City</div>
        <div>@item.State</div>
        <div>@item.Zip</div>
        <div>@item.ContactName</div>
        <div>@item.ContactEmail</div>
        <div>@item.County</div>
        <div>@item.Authorized</div>
        <hr />
    </div>
}

So I'm thinking it is instantiated here

@model IEnumerable<OilNGasWeb.ModelData.Clients>

but just incase I was wrong maybe it's instantiated in the Home controller in the Index Action?

 public ActionResult Index()
    {
        var Model = _db.Clients.ToList();

        return View();
    }

Please help me figure out why it's throwing this exception thanks. I wouldn't think you needed more code. but if you do let me know what M , V , C to post for you, as said above the data part works great.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Pakk
  • 1,299
  • 2
  • 18
  • 36
  • 4
    You'll need to pass the Model to the View as a parameter of the View() Method. – mboldt Jun 19 '13 at 17:46
  • 1
    Right, `View()` passes null as a Model. – neontapir Jun 19 '13 at 17:46
  • Almost all cases of `NullReferenceException` are the same. Please see "[What is a NullReferenceException in .NET?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-in-net)" for some hints. – John Saunders Jun 19 '13 at 17:50
  • Sry John, it wasnt that i didnt know what it was , but rather where to find the dang thing... but thanks – Pakk Jun 19 '13 at 20:22

1 Answers1

6
public ActionResult Index()
{
    var model = _db.Clients.ToList();

    return View(model);
}

You need to pass the model to the view, otherwise it will be null.

glosrob
  • 6,631
  • 4
  • 43
  • 73
  • Awesome .... thanks, atleast i didn't waste too much time on that issue :) thanks again will set as answered in about 3 min when it lets me – Pakk Jun 19 '13 at 17:55
  • There any way you would be able to tell me if I had a model with countys that are one-to-many with Clients model, if i can pass them both or atleast pass the client id with the county model? – Pakk Jun 24 '13 at 15:18
  • 1
    It's beyond the scope of this question but: short answer yes. Longer answer: review the concept of ViewModels https://www.google.co.uk/search?q=view+models+asp+net+3 – glosrob Jun 24 '13 at 16:33